Jerome P Mrozak
Jerome P Mrozak

Reputation: 1957

Node.js / Express: POST being turned into GET (code 302)

In brief, I have a login page where my POST request is turning into a GET in Express 4.

Here is the business part of my login page:

<form id='loginForm' action='/login' method='post'>
    <table>
        <tr>
            <td><input type='text' name='username' /></td>
        </tr>
        <tr>
            <td><input type='text' name='password' /></td>
        </tr>
        <tr>
            <td><button type='submit'>Submit</button></td>
        </tr>
    </table>
</form>

Here are routes I set:

// Express 4    
var router = express.Router();

router.get('/login', function(req, res) {
    res.render('./login.hbs', { message: req.flash('loginMessage') });
});

router.post('/login', passport.authenticate('local-login', {
    successRedirect: '/welcome',
    failureRedirect: '/login',
    failureFlash : true
}));

passport.use('local-login',
    new LocalStrategy(
        {
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback : true
        },
        function(req, email, password, next) {
            User.findOne({ 'authLocal.email' :  email }, function(err, user) {
            console.log('Inside local-login strategy with findOne A');
            [snip]

I put a breakpoint on the res.render for GET /login and in the findOne() call in the local-login strategy. When I click on the "Submit" button the breakpoint that catches things is in the router.get() code.

In the debugger the req.method is GET.

In the browser (Chrome) I'm told that I'm doing a POST to /login that returned 302. There is also a pending GET to /login with a 200 code. These two codes (302, 200) are when the debugger stops in router.get(). Even clearing the browser cache doesn't help.

Can someone tell me why my POST request isn't being honored?

Upvotes: 5

Views: 3860

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Simple Answer

Reason behind POST /login being turned into GET /login 302 is the redirection done by passport module.

See failureRedirect in following code:

router.post('/login', passport.authenticate('local-login', {
    successRedirect: '/welcome',
    failureRedirect: '/login',
    failureFlash : true
}));

It can happen when credentials provided are invalid or server fails to authenticate for any reason.

Happy Helping!

Upvotes: 1

Brennan
Brennan

Reputation: 1785

Looks like the strategy is local not local-login according to this documentation.

It also, looks like the first argument to the passport.use function should be the LocalStrategy object, not a string.

Give that a try!

Upvotes: 0

Related Questions