How to use jquery/ajax data for passportjs

前端 未结 3 440
梦谈多话
梦谈多话 2020-12-06 03:29

If I send a login request using the form fields action=\"/login\", method=\"post\", it works just fine. Similar to the code available here or here.

But

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 04:03

    Nobody can tell without looking at your server side code, AND which passport strategy you are using. For example,a snippet of the local strategy looks like this:

    function Strategy(options, verify) {
      // snip 
      this._usernameField = options.usernameField || 'username';
      this._passwordField = options.passwordField || 'password';
      // snip
    }
    // snip
    
    Strategy.prototype.authenticate = function(req, options) {
      options = options || {};
      var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
      var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);
      // snip
    

    }

    The fields you pass from jQuery need to match up to how you have it configured on the server side, and what that strategy is looking for. In this case if you are using a local strategy without configuring the username and password, it looks for the username and passport fields to be passed in either the req.body or req.query.

    So no - email will not work. However you can instantiate the Strategy by passing in the options object a field which overrides the default username e.g.,

    {
       username: 'email'
    }
    

    I have used this previously to authenticate passport via jQuery:

      var login = function (un, pwd) {
    
            $.ajax({
                type: "POST",
                dataType: 'json',
                data: { "email": un.val(), "password": pwd.val() },
                url: "/rest/login/?format=json",
                success: function (data) {
                    window.location.href = '/somewhereElse'
                }
            });
        }
    

    I suspect your dataType needs to be 'json' not 'html'

提交回复
热议问题