Payload error in jsonwebtoken

后端 未结 7 2081
谎友^
谎友^ 2021-02-01 16:50

I am making a web application using nodejs and angular cli I\'m using JWT to authenticate my login function . But when I process it threw this error

Err

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 17:34

    It fails at the line

    const token = jwt.sign(user, config.secret, {
    

    With error "Expected "payload" to be a plain object"

    Your user object is initialized here:

    User.getUserByUsername(username, (err, user)
    

    Which I assume is mongoosejs object, which contains many methods and is not "serializable". You could handle this by passing a plain object, by either using .lean() from mongoose or plain toJSON method:

    const token = jwt.sign(user.toJSON(), config.secret, {
      expiresIn: 604800 // 1 week
    });
    

提交回复
热议问题