'Express Login With Redirect Using Node.js
I'm trying to implement a basic login mechanism based on this answer: https://stackoverflow.com/a/8003291/5111904
In my backend I'm handling the login post
request like this:
app.post('/login', function (req, res) {
console.log(req.body);
if (req.body.user === 'normal' && req.body.password === '12345') {
req.session.user_id = 0; // This is failing (req.session is undefined)
res.redirect('/index');
} else {
res.send('Bad user/pass');
}
});
The server is using https
:
server = https.createServer(https_options, app).listen(PORT, HOST);
When the client is clicking the login button this code is getting executed:
function postLogin(){
var url = "/login";
var xhr = new XMLHttpRequest();
var data = {
user: userInput.value,
password: passwordInput.value
};
xhr.open("POST", url, true);
xhr.onreadystatechange = function (oEvent) {
if(xhr.readyState === 4){
// Checking status codes
if(xhr.status === 200){
onSuccess(xhr.responseText, xhr.responseType);
}
else{
console.log(xhr.status);
onError();
}
}
}
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
console.log("Sending this data: " + JSON.stringify(data));
xhr.send(JSON.stringify(data));
}
After the login the user should get redirected to the index page:
app.get('/index', (request, response) => {
response.render('main', {});
})
So I got this issues:
- In the first code snippet req.session is undefined
- In the secod snippet the value of (xhr.responseText) evaluates to the html of the index page (where the user should be redirected)
- How do I redirect the user to the index page in a proper way?
There will be only one valid user so this code is not intended to be used by many people and it should only provide a basic type of security.
Solution 1:[1]
There are really three issues here:
- Using session with express
In express, the if you want to use session, you need to initialize it as a middleware to your application. There is a detailed guide in it's documentation: https://github.com/expressjs/session.
Basically, you need something like this in you application before you write out your routes:
app.use(session({
secret: 'keyboard cat',
cookie: { secure: true }
}))
This middleware will add the session
method on your req
object and you can now use req.session
.
- Receiving the html value in
xhr.responseText
.
I believe you are misunderstanding how AJAX (or XMLHttpRequest to be particular) works. If the request server sends a redirect header, the browser automatically follows the redirect, you will not be aware of this, and at the end you are presented with the final response (I could not find any real documentation on this except this answer. So your AJAX request is following the redirection and sending you the final response.
- Proper way of redirecting to index page
The proper way of working with AJAX is to have all the control of how your page works on the front-end. So the responsibility of redirecting between pages also falls on the front-end. The best way forward in your case would be: send a request to /login
to log the user in. The response will have a status code that determines the success or failure (200 for success and may be 401 for failure). You can then check the status of the response and redirect.
On the back-end:
app.post('/login', function (req, res) {
if (req.body.user === 'normal' && req.body.password === '12345') {
req.session.user_id = 0;
res.status(200).send('User logged in');
} else {
res.status(401).send('Bad user/pass');
}
});
On the front-end:
xhr.onreadystatechange = function (oEvent) {
if(xhr.readyState === 4){
// Checking status codes
if(xhr.status === 200){
// user logged in
window.location = '/index';
}
else{
// login failed
console.log(xhr.status);
onError();
}
}
}
Solution 2:[2]
Follow the step by step process to create a login system in nodejs using expressjs framework with MySQL database - refer link - https://codeamend.com/blog/node-js-login-authentication-using-expressjs-and-mysql-with-example/
router.post('/submit_login', function(req, res, next) {
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM users WHERE email = ? AND password = ?', [email, password], function(err, rows, fields) {
if(err) throw err;
// if user not found
if (rows.length <= 0) {
req.flash('error', 'Please enter correct email and Password!')
res.redirect('/user/login')
} else {
// if user found
req.session.loggedin = true;
req.session.name = rows[0].username;
res.redirect('/user/home');
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Kaviya Manoharan |