I am working on a Node.js express application using JWT for authentication to access my admin page. I tested my routes with Postman and it works very well, the problem is in client side. I'll simplify my code and my question to make the question very clair.
My question is how can I get redirected to my admin page after the token has been stored locally with localStorage ?
I already try to solve this problem with ajax but the page still the same. I also tried window.location='/admin' but in this one I can't send a header that contain the token.
First my Server Side :
app.get('/admin', verifyToken, function(req, res, next) {
res.render('views/admin');
});
function verifyToken(req, res, next) {
var token = req.headers['access-token'];
if (!token)
return res.status(401).send({ auth: false, message: 'NO TOKEN PROVIDED' });
jwt.verify(token, config.secret_key, function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
console.log("Token is valid");
next();
});
}
Client Side :
function login(event) {
event.preventDefault();
let formData = new FormData(event.target);
fetch("/admin/login", {
method: 'POST',
body: formData
}).then(function (response) {
return response.json();
}).then(function (result) {
if (result.auth === true) {
localStorage.token = result.token;
//HERE IS THE PROBLEM
$.ajax({
type : "GET",
url : "/admin",
beforeSend: function(xhr){
xhr.setRequestHeader('access-token', localStorage.token);
},
success : function(result) {
//HERE IS THE PROBLEM
window.location='/admin';
}
});
} else {
console.log("Incorrect username or password.");
}
});
}
So how do I send the token in the headers like I did in Postman in client side and get redirected automatically, is there any method ? Many thanks.