Sunday, 19 March 2017

How to make app go to default route and on success to particular route 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. 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

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

<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



via user7350714

No comments:

Post a Comment