我在浏览器中将用户Cookie设置为jwt令牌,它设置成功,但当我尝试使用req.cookies获取该Cookie时,它给了我undefined和[Object:null prototype] {}这是我的程式码'
exports.isAuthenticated = asyncErrorHandler(async (req, res, next) => {
//fetching the jwt token from the cookie
const { token } = req.cookies;
console.log(req.cookies);
if (!token) return next(new ErrorHandler("plz log in first ", 400));
//verifying the given token matches the jwt stored token
const decodedData = jwt.verify(token, process.env.JWT_SECRET);
req.user = await userModel.findById(decodedData.id);
next();
});
这是我的express app.js文件
const express = require("express");
const errorMiddleware = require("./middleware/error");
const cookieParser = require("cookie-parser");
const bodyparser = require("body-parser");
const fileupload = require("express-fileupload");
const cors = require("cors");
const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(bodyparser.urlencoded({ extended: true }));
app.use(fileupload());
app.use(
cors({
credentials: true,
origin: "http://127.0.0.1:5173",
optionsSuccessStatus: 200,
})
);
// Route Imports
const productRoutes = require("./routes/productRoutes");
const userRoutes = require("./routes/userRoutes");
const orderRoutes = require("./routes/orderRoute");
const bodyParser = require("body-parser");
app.use("/api/v1", productRoutes);
app.use("/api/v1/user", userRoutes);
app.use("/api/v1", orderRoutes);
//error HAndler Middleware
app.use(errorMiddleware);
module.exports = app;
[![THIS iS THE eRROR i GOT IN THE tERMINAL ](https://i.stack.imgur.com/5sons.png)](https://i.stack.imgur.com/5sons.png)
我尝试了cOOKIE-PARSEER,也有CORS在我的EXPRESS应用程序文件..我设置cookie密钥为令牌
1条答案
按热度按时间vyswwuz21#
req.cookies
不是 获取 cookie 的 正确 方法 如果 你 想 获取 cookie , 它 在 头 中 , 所以 你 必须 从 请求 的 头 中 获取 cookie , 如下 所 示 :中 的 每 一 个