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

▼魔方 西西 提交于 2019-12-10 15:15:44

问题


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?


回答1:


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!




回答2:


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!



来源:https://stackoverflow.com/questions/28599167/node-js-express-post-being-turned-into-get-code-302

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!