weixin_33694620 2017-04-18 12:24 采纳率: 0%
浏览 223

NodeJS + Ajax +登录表单

I'm making an AJAX login with NodeJS. This is my current code:

routes.js:

app.post('/login', (req, res, next) => {
    passport.authenticate('local-login', (err, user, info) => {
        if (err)
            return next(err);

        if (!user)
            return res.json({type: 'error', response: info});

        req.logIn(user, (err) => {
            if (err) 
                return next(err);

            //return res.json({type: 'success', response: user});
            return res.redirect(req.originalUrl);
            //return res.redirect(req.get('referer'));
        });
    })(req, res, next);
});

custom.js

let login = () => {
$.post( "/login", { email: $('#inputUsername').val(), password: $('#inputPassword').val() })
.done((data) => {
    if(data.type === 'error'){
        $( "#logFormError" ).html('<b>Error:</b> ' + (data.response.message ? data.response.message : data.response));

        if(!$("#logFormError").is(":visible"))
            $( "#logFormError" ).toggle();
    }else{
        if($("#logFormError").is(":visible"))
            $( "#logFormError" ).toggle();
    }
})
.fail((error) => {
    $( "#logFormError" ).html('<b>Error:</b> ' + error);

    if(!$("#logFormError").is(":visible"))
        $( "#logFormError" ).toggle();
})}

replaysController.js (the page I'm displaying the login form right now):

res.render('../views/pages/replays', {replay: replay, user: req.user});

What I'm trying to achieve is to have the page I'm currently in with the new login info. I don't want to use client javascript to play with the different items of the page because the page may be totally different (home, replays, shop, forums...) so elements aren't the same and it's not generic.

As you can see, I've been already testing res.redirect(req.get('referer')); and others but the page doesn't redirect, it just makes the request and stays there.

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33721427 2017-04-18 12:39
    关注

    res.redirect() won't redirect the browser page, just the AJAX request. You can probably verify this by using the network tab of the inspection tools in your browser to view the initial AJAX request, and subsequent AJAX request following a 301 response from the initial request.

    I imagine that you don't want the AJAX request to be redirected, you want the user's browser to be redirected. In the case of a successful login, I'd suggest you reply with a JSON blob containing a successful status indicator, and the URL to redirect to. You can then use javascript on the front end to redirect the user's browser to the location that has been returned from your AJAX endpoint by setting window.location.href.

    评论

报告相同问题?