【问题标题】:Complete user profiles完整的用户资料
【发布时间】:2021-04-10 08:06:26
【问题描述】:

我想为当前登录的用户做一个“完整的用户配置文件”,但是当我用邮递员测试 api 时,给出的结果显示为“未经授权”。顺便说一句,我正在使用护照中间件。任何提示和帮助都非常感谢提前:)

下面是我的更新代码:

router.post('/myprofile', passport.authenticate('jwt',{session: false}),
(req,res)=>{
    const {errors, isValid}= validateProfileInput(req.body);
    if(!isValid){
        res.status(400).json(errors);
    }
    const profileFields={};
    profileFields.user =req.user.id;
    if(req.body.icNumber)profileFields.icNumber= req.body.icNumber;
    if(req.body.phoneNumber)profileFields.phoneNumber= req.body.phoneNumber;
    if(req.body.dob)profileFields.dob= req.body.dob;
    if(req.body.gender)profileFields.gender= req.body.gender;
    if(req.body.address1)profileFields.address1= req.body.address1;
    if(req.body.address2)profileFields.address2= req.body.address2;
    if(req.body.city) profileFields.city=req.body.city;
    if(req.body.state) profileFields.state=req.body.state;
    if(req.body.zip) profileFields.zip=req.body.zip;

    Profile.findOne({user:req.user.id}).then(profile=>{
        if(profile){
            //update
            Profile.findOneAndUpdate(
                {user:req.user.id},
                {$set: profileFields},
                {$set: { status: true }}
            ).then(profile=>{
                res.json(profile);
            })
            // save profile
            new Profile(profileFields).save().then(profile=>res.json(profile))
        }
    })
  }
)

邮递员标题:

邮递员正文:

邮递员结果:

【问题讨论】:

  • 在您应该使用的标题旁边有一个Authorization 选项卡。你试过吗?
  • passport.authenticate('jwt'...表示策略为jwt,因此授权头应为Authorization: jwt eyJ....
  • 我已经尝试过 sinanspd 和 jps 建议的 ans,但它不能工作

标签: mongoose jwt passport.js mern


【解决方案1】:

当您使用jwt 创建令牌时,请使用根据您自己的数据创建令牌的函数...最终令牌是token: "Bearer " + signedToken,就像这样...

const jsonwebtoken = require('jsonwebtoken');
function issueJWT(user) {
  const _id = user._id;

  const expiresIn = '1d';

  const payload = {
    sub: _id,
    iat: Date.now()
  };

  const signedToken = jsonwebtoken.sign(payload, PRIV_KEY, { expiresIn: expiresIn, algorithm: 'RS256' });

  return {
    token: "Bearer " + signedToken,
    expires: expiresIn
  }
}

当你想得到请求时,像这样设置你的邮递员

或者在header Authorization Key: Breare + spcace + Token

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多