首页 > 解决方案 > 无法在我的 MERN 堆栈项目中获取 JSON 格式的用户配置文件

问题描述

我基本上在我的 MERN Stack 项目上工作,在后端节点部分,过去几天我遇到的问题是,我正在尝试访问这个受保护的路由,http://localhost:3555/profile/我,为了访问这条受保护的路线,我正在发送一个令牌,但问题是当我尝试在 POSTMAN 上这样做时,我没有得到任何响应,并且它不断显示我,发送仅请求。

我相信我的代码是正确的,但我仍然不知道为什么它会卡住并且我无法得到回复。

在此处输入图像描述

并且,这是我试图以 JSON 格式获取用户配置文件的代码:

const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const Profile = require("../../models/Profile");
const User = require("../../models/User");

//@route GET api/profile/me (Only Fetching My Profile , not all the profiles)
//@desc Get Current User's Profile
//@access Private;

router.get("/me", auth, async (req, res) => {
  try {
    const profile = await Profile.findOne({
      user: req.user.id,
    }).populate("user", ["name", "avatar"]);

    if (!profile) {
      return res.status(400).json({ msg: "there is no profile for this user" });
    }

    res.json(profile);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

module.exports = router;



这是我的身份验证中间件的代码:

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

//Our Middlware Function
module.exports = function (req, res, next) {
  //Get the Token From the Header :
  const token = req.header("x-auth-header");

  //Check if no token , available for the Protected Route  :
  if (!token) {
    return res.status(401).json({ msg: "No Token , Authorization Denied" });

    //Verifying the Token :
    try {
      const decoded = jwt.verify(token, config.get("jwtSecret"));
      req.user = decoded.user;
      next();
    } catch (err) {
      //TODO : To be Executed , in case if the token is not valid :
      res.status(401).json({ msg: "Token is not valid" });
    }
  }
};


标签: node.jsexpress

解决方案


我认为您在中间件中缺少一个右括号:

if (!token) {
  return res.status(401).json({ msg: "No Token , Authorization Denied" });
}
// Verifying the Token :
try {
  const decoded = jwt.verify(token, config.get("jwtSecret"));
  req.user = decoded.user;
  next();
} catch (err) {
  //TODO : To be Executed , in case if the token is not valid :
  res.status(401).json({ msg: "Token is not valid" });
}

推荐阅读