mongoose Express Cors缺少允许凭据

b4qexyjb  于 2023-08-06  发布在  Go
关注(0)|答案(3)|浏览(137)

我的Express服务器配置如下:

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import helmet from "helmet";
import morgan from "morgan";
import cookieParser from "cookie-parser";
import categoryRoutes from "./routes/category.js";
import subCategoryRoutes from "./routes/subCategory.js";
import expenseRoutes from "./routes/expense.js";
import userRoutes from "./routes/user.js";
import { authMiddleware } from "./middleware/authMiddleware.js";

dotenv.config();

const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));

app.use(morgan("common"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
  cors({
    origin: *********************,
    credentials: true,
  })
);

app.use("/category", authMiddleware, categoryRoutes);
app.use("/subCategory", authMiddleware, subCategoryRoutes);
app.use("/expense", authMiddleware, expenseRoutes);
app.use("/user", userRoutes);

const PORT = process.env.PORT || 9000;

mongoose
  .connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(async () => {
    app.listen(PORT, () => {
      console.log(`Server running on port: ${PORT}`);
    });
  })
  .catch((error) => {
    console.log(`${error} connecting to DB`);
  });

字符串
但是对于任何不是“/user”的路由,我都会收到一个“CORS Missing Allow Credentials”错误,其中包含以下请求头:

Accept
    */*
Accept-Encoding
    gzip, deflate, br
Accept-Language
    en-US,en;q=0.5
Connection
    keep-alive
Cookie
    jwt=*************************
Host
    *************************
Origin
    https://*********************
Referer
    https:/**********************/
Sec-Fetch-Dest
    empty
Sec-Fetch-Mode
    cors
Sec-Fetch-Site
    cross-site
TE
    trailers
User-Agent
    Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0


我正在为其他路由使用中间件,所以可能会导致问题,如果是这样,它是:

import jwt from "jsonwebtoken";

export const authMiddleware = async (req, res, next) => {
  const { id, token } = req.cookies;
  console.log(id, token);
  try {
    if (id) {
      req.userId = id;
    res.setHeader(
      "Access-Control-Allow-Origin",
      "**************************"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);
      next();
    }

    if (token) {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      if (decoded) {
        const userId = decoded.id;
        req.userId = userId;
    res.setHeader(
      "Access-Control-Allow-Origin",
      "**************************"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);
        next();
      }
    }
  } catch (error) {
    throw new Error("Not authorized!");
  }
};


我想我的cors和 Helm 配置是错误的设置,但这里是我击中的端点之一,我没有任何标题设置在它的响应:

router.get("/expenses/", async (req, res) => {
  const userId = req.userId;
  console.log(userId);

  try {
    const expenses = await Expense.find({
      userId: userId,
    })
      .populate("subCategory")
      .populate("category")
      .exec();

    const mappedExpenses = expenses.map((expense) => ({
      id: expense._id,
      date: expense.date,
      price: expense.price,
      userId: expense.userId,
      category: expense.category.name,
      subCategory: expense.subCategory.name,
    }));
    console.log("user expenses: ", mappedExpenses);
    res.status(200).json(mappedExpenses);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
});


在/expense/expenses请求上添加I'm getting a 502 bad gateway和strict-origin-when-cross-origin的引用者策略可能很有用
最后,我使用rtk query通过以下basequery进行这些API调用:

baseQuery: fetchBaseQuery({baseUrl: import.meta.env.VITE_BASE_URL, credentials: 'include'}),


env var与服务器url匹配,所以没有问题,前端登录组件设置cookie如下:

loginUser(values)
            .unwrap()
            .then((res) => {
              console.log(res._id);
              setCookie("id", res._id, {
                path: "/",
                sameSite: "none",
                secure: true,
              });

              toast.success("logged in!");

              navigate("/dashboard", { replace: true });
            })
            .catch((e) => {
              console.log(e);
            });

vsmadaxz

vsmadaxz1#

很高兴地报告,我花了10个小时才发现我在登录时设置的cookie是“jwt”,我在中间件中搜索一个名为“token”的cookie。

y3bcpkx1

y3bcpkx12#

我不太确定,但它可能与设置cookie安全有关。

setCookie("id", res._id, {
                path: "/",
                sameSite: "none",
                secure: true,
          });

字符串
在这种情况下,您不应该将 * 作为允许的原点。我想配置cors可以解决这个问题。
allowedOrigin.js:

const allowedOrigins = ["your-frontend-app-port"];

module.exports = allowedOrigins;


corsOptions.js:

const allowedOrigins = require("./allowedOrigins");

const corsOptions = {
  origin: (origin, callback) => {
    if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
  optionsSuccessStatus: 200,
};

module.exports = corsOptions;


在index/server.js文件中

app.use(cors(corsOptions));

不确定。只是一种直觉。

5w9g7ksd

5w9g7ksd3#

删除此项或将其设为false,凭据:真实
后端和前端

相关问题