我遇到了一个问题,当我试图在“localhost:3300/API/user/all”(或任何其他)中使用get方法时,它在Postman““error”中显示了一个错误:“无效令牌”。我把我的令牌在授权头使用格式“承载“。我不知道是什么引起的。
我的user.js
const express = require("express");
const router = express.Router();
const User = require("../models/user");
const {
verifyToken,
verifyTokenAndAdmin,
} = require("../routes/verifyToken");
router.get("/:id", verifyToken, async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get("/", verifyTokenAndAdmin, async (req, res) => {
try {
const users = await User.find({});
res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.put("/:id", verifyToken, async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.address = req.body.address;
user.phone = req.body.phone;
user.dateOfBirth = req.body.dateOfBirth;
const updatedUser = await user.save();
res.json(updatedUser);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.delete("/:id", verifyTokenAndAdmin, async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
await user.remove();
res.json({ message: "User deleted successfully" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
我的verifyToken.js
const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) => {
const authtoken = req.header("Authorization");
const token = authtoken.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "No token, authorization denied" });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
console.log(token)
res.status(401).json({ error: "Invalid token" });
}
};
const verifyTokenAndAdmin = (req, res, next) => {
verifyToken(req, res, () => {
// Check if the user is an admin
if (!req.user.isAdmin) {
return res.status(403).json({ error: "Admin access required" });
}
next();
});
};
const verifyTokenAndAuth = (req, res, next) => {
verifyToken(req, res, () => {
next();
});
};
module.exports = {
verifyToken,
verifyTokenAndAdmin,
verifyTokenAndAuth,
};
型
x1c 0d1x的数据
1条答案
按热度按时间pqwbnv8z1#
你检查过服务器日志了吗
看起来你应该在verifyToken.js中更改
verifyToken
,将错误记录在catch块中,而不是标记中。这将使您更接近调试。最有可能的错误是在这一行中抛出的:
字符串
验证失败或
JWT_SECRET
无效。更改下面的行以查看错误:
型