简体   繁体   中英

Ajax call to passport does not run the authenticate middleware

This is the client side code to request authentication

    $("form#login-form").on("click", "#submit", function (e) {
      e.preventDefault();
      $.ajax({
        url: "/login",
        type: "POST",
        data: JSON.stringify({ email: $("#email").val(), password: $("#password").val() }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
      }).done(function (response, textStatus, jqXHR) {

        utils.clearErrors();
        location.reload();
      }).fail(function (jqXHR, textStatus, errorThrown) {

        // handle the error
        utils.handleError(jqXHR, textStatus, errorThrown);
      })
    });

Below is the node API for passport authentication

    app.post('/login', passport.authenticate('local-login'), (req, res, next) => {
      return res.json({ user: req.user });
    });

Passport.authenticate function does not call the middleware function in case of ajax call but if page is submitted using form then it works perfectly.

the function you are u calling to authenticate is

passport.authenticate('local');

It aslo depends the module you have included. Please check the code here on https://github.com/rupalipemare/Mongoose-Demo , wherein there is complete example demonstrating passport authentication. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM