简体   繁体   English

需要帮助在节点js应用程序中进行路由

[英]Need help for routing in node js application

I have a nodejs application,where I want user to go to login page by default if he tries to access any route or any file(html/js).If the credentials are correct he should go to /index page. 我有一个nodejs应用程序,我希望用户默认进入登录页面,如果他试图访问任何路由或任何文件(html / js)。如果凭据是正确的,他应该去/索引页面。 I've added post call in my main app.js file and it is working from postman,but unaware of how to use in my node app itself. 我在我的主app.js文件中添加了post call,它正在postman中工作,但不知道如何在我的节点应用程序本身中使用。

app.js 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
}
});

In login folder I have my login.html and my login .js 在登录文件夹中,我有我的login.html和我的登录.js

login.html 的login.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>

How can I call login function so that it uses the above post call from my app.js and on success it goes to index page and also by default it should go to login page..Can some one help here 我如何调用登录功能,以便它使用我app.js上面的帖子调用,并成功后进入索引页面,默认情况下也应该进入登录页面。可以在这里帮助一些

You need to use a middleware in node. 您需要在节点中使用中间件。 In your case, let's call it auth, it will check the credentials, if they are correct it will call the next handler in the chain, if not, it will issue a response with 401 (or 403 if forbidden) status code to the client. 在你的情况下,让我们称之为auth,它将检查凭证,如果它们是正确的,它将调用链中的下一个处理程序,如果不是,它将向客户端发出401(或403,如果被禁止)状态代码的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM