node.js - 无法在我的 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" });
}
}
};
解决方案
我认为您在中间件中缺少一个右括号:
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" });
}
推荐阅读
- python - 如何在启动 (macOS) 上运行 Python 脚本?
- typescript - Typescript 接口为特定属性设置默认值
- c# - 为什么我的子弹穿过我的敌人而没有检测到碰撞?
- html - 我该怎么做才能保持动态列表?
- vb.net - 无法将参数传递给 Telerik 报告
- c# - Xamarin.Mac 应用程序在与最终用户的文件系统交互时挂起
- javascript - react-native 错误:[未处理的承诺拒绝:错误:获取 Expo 令牌时遇到错误:TypeError:网络请求失败。]
- angular - ngForOf 中的重复 ID 生成 - Angular
- php - 增加 WooCommerce 购物车中每个类别计数的运费
- c - 试图从另一个 char 指针分配一个 char 指针。为什么会出现段错误?