You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复CORS中include Credentials相关的跨域请求错误

问题:加入购物车/收藏API触发CORS跨域错误,登录注册API正常
  • 仅调用加入购物车和收藏(add fav)API时出现CORS错误,登录/注册API无异常,此前功能正常,昨晚开始出现问题。

错误详情

Access to XMLHttpRequest at 'https://book-store-web-app-jl7e.onrender.com/api/v1/addFavourites' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

后端代码

const express = require("express");
require("dotenv").config();
const DBConnect = require("./config/DatabaseConfig");
const app = express();
const cors = require("cors");

DBConnect();

app.use(express.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:5173");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, id, bookid"
  );
  next();
});

const corsOptions = {
  origin: [
    "http://localhost:5173", // Your frontend URL
    "My actual url of render", // Your production URL
  ],
  methods: ["GET", "POST", "PUT", "DELETE"],
  allowedHeaders: ["Content-Type", "Authorization", "id", "bookid"],
  credentials: true, // Allow credentials in the response
};

app.use(cors(corsOptions));
app.options("*", cors(corsOptions));

问题原因

你同时手动设置了CORS响应头,又使用cors官方中间件,两者配置冲突导致预检请求的Access-Control-Allow-Credentials头为空。手动设置的头与中间件配置重复,且执行顺序问题导致预检请求未正确获取凭证权限配置。

修复步骤

  1. 删除手动设置CORS头的中间件
    移除这段自定义的CORS头配置代码,cors库已能完整处理所有CORS规则,重复设置会引发冲突:

    // 删掉以下代码块
    app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "http://localhost:5173");
      res.header("Access-Control-Allow-Credentials", "true");
      res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      res.header(
        "Access-Control-Allow-Headers",
        "Content-Type, Authorization, id, bookid"
      );
      next();
    });
    
  2. 调整中间件顺序并确认配置
    确保cors中间件放在所有路由和express.json()之前,同时替换生产环境的真实URL:

    const express = require("express");
    require("dotenv").config();
    const DBConnect = require("./config/DatabaseConfig");
    const app = express();
    const cors = require("cors");
    
    DBConnect();
    
    // 先配置CORS,再处理请求体和路由
    const corsOptions = {
      origin: [
        "http://localhost:5173", // 前端本地URL
        "你的Render生产环境实际URL", // 替换为真实地址
      ],
      methods: ["GET", "POST", "PUT", "DELETE"],
      allowedHeaders: ["Content-Type", "Authorization", "id", "bookid"],
      credentials: true, // 允许携带凭证
    };
    
    app.use(cors(corsOptions));
    app.options("*", cors(corsOptions));
    
    app.use(express.json());
    
    // 挂载你的业务路由
    // app.use("/api/v1", yourRouter);
    
  3. 验证前端请求配置
    确认前端发起请求时开启了withCredentials:

    • 若使用axios:axios.defaults.withCredentials = true或在请求配置中添加withCredentials: true
    • 若使用原生XMLHttpRequest:xhr.withCredentials = true

内容的提问来源于stack exchange,提问作者Surani Faizan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 06:31:00