这是我的路由文件中的代码(users.js)

User.findOne({linkedin_id: req.body.linkedin_id}, function(err, linkedinUser) {
    if(err) {
      console.log('err in finding linkedin user '+err);
    }
    // if user exits
    else if(linkedinUser) {
      console.log('user exist');
      const token = jwt.sign(linkedinUser, config.secret, {expiresIn: 604800});
      res.json({success: true, token: 'JWT '+token, user: {
          id: linkedinUser._id,
          linkedin_id: linkedinUser.linkedin_id,
          name: linkedinUser.name,
          username: linkedinUser.username,
          email: linkedinUser.email,
          lkprofilePic: linkedinUser.profilePic
        }, msg: 'user exits'
      });
    }
    // if user doesn't exist
    else {
      User.create({
        linkedin_id: req.body.linkedin_id,
        name: req.body.name,
        username: req.body.username,
        email: req.body.email,
        lkprofilePic: req.body.lkprofilePic
      }, function(err, result) {
        if(err) {
          res.json({success: false, msg: 'failed to add'})
          console.log('error in adding the data '+err);
        }
        else if(result) {
          const token = jwt.sign(linkedinUser,config.secret,{ expiresIn: 604800 });
          res.json({success: true, token: 'JWT '+token, user: {
            id: result._id,
            linkedin_id: result.linkedin_id,
            name: result.name,
            username: result.username,
            email: result.email,
            lkprofilePic: result.profilePic
          }, msg: 'User added '  });
        }
      });
    }
  });

这来自config -> secret
module.exports = {
    secret: 'bigfish'
  }

这是我在nodejs控制台中遇到的错误



但是数据正在保存在数据库中,并且不会返回
res.json({success: true, token: 'JWT '+token, user: {
            id: result._id,
            linkedin_id: result.linkedin_id,
            name: result.name,
            username: result.username,
            email: result.email,
            lkprofilePic: result.profilePic
          }, msg: 'User added '  });

最佳答案

问题在于您对 token 进行签名的方式

您使用的用户是 Mongoose 的返回用户,因此您需要使用 YOUR_USER.toJSON 。如果用户不是 Mongoose 用户,请使用 JSON.stringify(YOUR_USER)代替

将您的代码更改为

const token = jwt.sign({linkedinUser}, config.secret, {expiresIn: 604800});
//if you want to set expiration on the token


const token = jwt.sign(linkedinUser.toJSON(), config.secret);
//if you just want to sign the token without setting the expiration

关于javascript - 预期 “payload”是普通对象: MEAN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52781477/

10-09 22:23