Reputation: 349
I'm trying to make a simple authentication page using Node with Express framework.
At this moment, I'm not particularly worried about the weak protection.
However, my route file is displaying weird behavior.
Here is the code:
var express = require('express');
var router = express.Router();
var admin = require("../controllers/admin");
router.get('/', function(req, res) {
console.log('Entered top route.');
if(req.body.isAuthenticated) {
res.redirect('admin/index');
} else {
res.redirect('admin/login');
}
});
router.post('/authenticate', function(req,res) {
if(req.body.pword == "key") {
console.log("Resetting body.isAuth'ed");
req.body.isAuthenticated = true;
console.log("New val: " + req.body.isAuthenticated);
res.redirect('admin/index');
} else {
console.log("Failed login attempt: " + req.body.pword);
res.redirect('admin/login');
}
});
router.get('/login', admin.login);
router.get('/index', admin.index);
module.exports = router;
The idea is that the route is entered, upon which we hit the top route (properly logged by console). This redirects based on whether a req variable is set. This all works properly, and the login (I'm using jade templating) is properly rendered. The login file has a form which calls back to this routing file with 'admin/authenticate'. This also works properly; I'm able to properly retrieve the input (confirmed via console logs). However, the actions I take in the /authenticate/ function, even though they are the exact same thing I do in the '/' route right above, fail. I get 404's and Express Not Found printouts which are entirely useless.
My console properly logs 'Failed login attempt' or 'Resetting body...New val: true", but then doing the exact same res.redirect that is initially done in the router.get('/') method above fails, whereas the res.redirects in that function properly redirect and render the correct values.
Any ideas what could be wrong? I could post the admin.login/admin.index methods in the controllers/admin file. However, they're very simple and I think this error stems from a basic misunderstanding of the difference between get and post methods or something (this is my first time using Node).
Thanks!
Upvotes: 0
Views: 87
Reputation: 1210
I think the issue is because of the relative path.
Doing res.redirect('admin/index')
from path /
and path /authenticate
is not same.
res.redirect('admin/index')
from /authenticate
will redirect user to /authenticate/admin/index
, may be thats why it is giving 404.
Try to change res.rediret('admin/index')
to res.redirect('/admin/index')
in authenticate callback.
Upvotes: 2