【问题标题】:Getting boolean value false while applying jsonwebtoken and testing api in POSTMAN在 POSTMAN 中应用 jsonwebtoken 和测试 api 时获取布尔值 false
【发布时间】:2020-10-03 07:52:42
【问题描述】:
  • 在这个项目中,我在对每条路由进行编码后对其进行测试。当我测试我的身份验证时,我得到了我的 jsonwebtoken(在应用 post 请求后从邮递员那里)。现在当我将标题键设置为:x-auth-token 和它的值是 jwtwebtoken(我从邮递员那里得到的),而不是使用 id 获取存储在 mongodb 数据库中的相同数据,它只显示一个布尔值“false”。控制台中没有显示错误。我不确定我要去哪里错了,请帮忙*

中间件 auth.js 文件

const jwt=require("jsonwebtoken");
const config=require("config");

module.exports=function(req,res,next){
    //get token from header
    const token=req.header("x-auth-token");

    //check if not token
    if(!token){
       return res.status(401).json({msg:"No token authorization"});

    }
    //verify token
    try{
const decoded=jwt.verify(token,config.get("jwtSecret"));
req.user=decoded.user;
next();
    }catch(err){
res.status(401).json({msg:"Token is not valid"});
    }
} ;

路由 api auth.js 文件

const express=require("express");
const router=express.Router();
const auth =require('../../middleware/auth');

const User = require('../../models/User');


//@route  Get api/auth
//does    test route
//@acess Public
router.get("/",auth,async (req,res) =>{
    try{
        const user=await User.findById(req.user.id).selected("-password");
        res.json(user);

    }catch(err){
        console.error(err.message);
        res.status(500).send("server error");

    }
});

module.exports=router;

这是我在从邮递员发送 get 请求时得到“错误”的 url

【问题讨论】:

标签: routes jwt postman


【解决方案1】:

没有人回答这个问题。经过一番头脑风暴,我终于得到了答案。在我的 json 文件中,为密码添加另一个字段,如下所示

password:{
          select:false
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2020-10-01
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多