我正在开发 MERN 堆栈应用程序(MongoDB、Express、React、Node.js)。在前端,我使用 Axios 进行 HTTP 请求。当我尝试在 Authorization 标头中发送 JWT 时,就会出现问题 — 服务器响应 401 Unauthorized 错误。
这是我到目前为止所做的:
我从前端的 localStorage 检索令牌。
我以 Bearer
前端代码:
import React, { useEffect } from "react";
import axios from "axios";
const ShowDish = () =\> {
useEffect(() =\> {
const fetchDishes = async () =\> {
try {
const token = localStorage.getItem("token");
if (!token) {
throw new Error("Token is missing! Please log in again.");
}
const response = await axios.get("http://localhost:5000/api/dishes", {
headers: {
Authorization: Bearer ${token},
},
});
console.log("Dishes:", response.data);
} catch (error) {
console.error("Error fetching dishes:", error);
}
};
fetchDishes();
}, \[\]);
return \<div\>Loading dishes...\</div\>;
};
export default ShowDish;
后端代码:
const jwt = require("jsonwebtoken");
const express = require("express");
const app = express();
const JWT_SECRET = "supersecretkey"; // (Store this in a .env file)
app.use(express.json());
// Generate token during login
app.post("/api/login", (req, res) =\> {
const { email, password } = req.body;
// Example user (in a real app, validate against the database)
const user = { id: "123", email, role: "user" };
const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: "1h" }
);
res.json({ token });
});
中间件
const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) =\> {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ message: "Not authenticated" });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(403).json({ message: "Invalid token" });
}
};
const authenticateToken = (req, res, next) =\> {
const authHeader = req.headers\["authorization"\];
const token = authHeader && authHeader.split(" ")\[1\];
if (!token) {
return res.status(401).json({ message: "Token is missing" });
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) =\> {
if (err) {
return res.status(403).json({ message: "Invalid token" });
}
req.user = user;
next();
});
};
受保护端点:
app.get("/api/dishes", verifyToken , (req, res) =\> {
res.json({ message: "Here are the dishes!", user: req.user });
});
const PORT = 5000;
app.listen(PORT, () =\> console.log(Server is running on port ${PORT}));
预期行为:
When sending a GET request to http://localhost:5000/api/dishes with a valid token in the Authorization header, I expect to receive a response with data (e.g., the list of dishes).
实际行为:
AxiosError: Request failed with status code 401
我尝试过的:通过在 jwt.io 上解码来验证令牌是否正确。确认令牌在授权标头中作为 Bearer
看起来您首先尝试从 cookie 中检索令牌,如果不存在则返回 401:
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ message: "Not authenticated" });
}
也许您不应该在此处结束中间件代码,而是让它通过并检查标头,就像您在下面所做的那样。