通过Nodejsexpress路由传递cookie

问题描述 投票:0回答:1

我有一个服务器,我使用 jws 生成一个令牌并将其存储在 cookie 中,但是当我尝试验证路由器时找不到 cookie,它只是返回未定义

快速路由器

const { adminAuth } = require("../middleware/auth");
router.route("/deleteUser").delete(adminAuth, deleteUser);

中间件/身份验证

exports.adminAuth = (req, res, next) => {
  console.log(req.cookies);
  const token = req.cookies.jwt;
  if (token) {
    jwToken.verify(token, jwtSecret, (err, decodedToken) => {
      if (err) {
        return res.status(401).json({ message: "Not authorized" });
      } else {
        if (decodedToken.role !== "admin") {
          return res.status(401).json({ message: "Not authorized" });
        } else {
          next();
        }
      }
    });
  } else {
    return res
      .status(401)
      .json({ message: "Not authorized, token not available" });
  }
};

我已经检查过 adminAuth 是否有效,但当我通过路由器访问它时它不起作用。我期望它只会通过路由器,但显然 cookie 不会通过路由器

javascript node.js express cookies jwt
1个回答
0
投票

我认为您面临这个问题是因为您的应用程序中未正确解析 cookie。

  1. 首先,安装
    cookie-parser
  • npm i --save cookie-parser
    yarn add cookie-parser
  1. 之后请确保将其设置到您的服务器:

const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();

app.use(cookieParser()); // use this

  1. 确保 cookie 设置正确。

//Send the cookie to the client from whatever route you have (eg: login route)
res.cookie("jwt", token, {
  httpOnly: true, // it is to prevent client-side scripts from accessing the cookie
  secure: process.env.NODE_ENV === "production", // only send over HTTPS in production (process.env is environmental variable. You can access it by npm i -s dotenv or yarn add dotenv and require it at the top of your server/backend and create a .env file and write NODE_ENV=developement or production inside of it)
  sameSite: "strict", // prevent CSRF
  maxAge: 24 * 60 * 60 * 1000 // cookie expires after 1 day. It is in milliseconds
});

//And to remove the cookie, if you have a logout route
res.clearCookie("jwt");

  1. 再次检查客户请求:

/******************************************************************
**                  If you are using fetch                       **
******************************************************************/

fetch('/deleteUser', {
  method: 'DELETE',
  credentials: 'include', // do this to make sure that you are sending cookies
});

/******************************************************************
**                  If you are using axios                       **
******************************************************************/

axios.delete('/deleteUser', {
  withCredentials: true, // do this to make sure that you are sending cookies
});

  1. 检查 cors 配置(如果您正在处理跨源请求)。

const cors = require("cors");

app.use(cors({
  origin: 'http://your-client-url', // allow only your client app url
  credentials: true // enable credentials (cookies) to be sent
}));

  1. 如果应用程序仍然无法工作(如果您正确遵循我的说明,应该可以),我将重新启动电脑并再次运行代码。如果问题仍然存在,我会在新文件中重写代码并从头开始尝试。
© www.soinside.com 2019 - 2024. All rights reserved.