gpt4 book ai didi

javascript - 需要在 Node js 应用程序中进行路由帮助

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:31 25 4
gpt4 key购买 nike

我有一个nodejs应用程序,如果用户尝试访问任何路由或任何文件(html/js),我希望用户默认转到登录页面。如果凭据正确,他应该转到/index页面。我在我的主 app.js 文件中添加了 post 调用,它正在 postman 中工作,但不知道如何在我的 Node 应用程序本身中使用。

app.js

app.get('*',function (req, res) {
res.redirect('/login');
res.sendFile(path.join(__dirname+'/login/login.html'));
});

app.get('/index',function(req,res){
res.sendFile(path.join(__dirname+'/index/index.html'));//on success of login it should be here
});

app.post('/login',function(req,res){
var username = req.headers.uname;
var password = req.headers.pwd;
var uname = "*****";
var pwd = "*******";
var login = false;
if(uname == username && pwd == password){
console.log("success");
login = true;
}
else{
console.log("fail");
login = false;
}
if(login == true){
res.send("Hello");//It should route to my /index page
}else{
res.send("Bad luck"); //Invalid credentials
}
});

在登录文件夹中,我有我的login.html 和我的login .js

登录.html

<html>
<head>
<script src="/login.js"></script>
</head>
<body>
<div>
Username:<input type="text" id="uname">
</div>
<div>
Password:<input type="text" id="pwd">
</div>
<div>
<button type="submit" onclick="login();">Login</button>
</div>
</body>
</html>

我如何调用登录函数,以便它使用我的 app.js 中的上述 post 调用,成功后它会转到索引页面,并且默认情况下它应该转到登录页面。有人可以在这里提供帮助吗

最佳答案

您需要在 Node 中使用中间件。在您的情况下,我们将其称为 auth,它将检查凭据,如果正确,它将调用链中的下一个处理程序,如果不正确,它将向客户端发出带有 401(如果被禁止,则为 403)状态代码的响应。

关于javascript - 需要在 Node js 应用程序中进行路由帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com