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

Strapi v5如何配置CORS源?跨域错误及配置不生效排查

解决Strapi中Credentials模式下的CORS错误

问题分析

当请求启用withCredentials: true时,浏览器要求Access-Control-Allow-Origin必须是具体的源地址,不能使用通配符*,同时响应头必须包含Access-Control-Allow-Credentials: true。你的Strapi配置存在两处关键问题:

  1. 配置项header是笔误,正确字段名应为headers
  2. 缺少显式开启凭证允许的配置项

正确的CORS配置

修改config/middlewares.ts文件,修正字段并补充凭证配置:

export default [
  "strapi::logger",
  "strapi::errors",
  "strapi::security",
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      // 允许的请求头,可使用通配符或具体字段列表
      headers: '*',
      // 指定允许的前端源地址,替换为你的实际地址
      origin: ['http://localhost:3000'],
      // 必须开启此项,允许请求携带凭证
      credentials: true
    }
  },
  "strapi::poweredBy",
  "strapi::query",
  "strapi::body",
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
];

关键注意事项

  • 重启Strapi服务:中间件配置修改后必须重启服务才能生效,热重载不会同步这类配置变更
  • 源地址准确性:确保origin数组中的地址和前端实际运行地址完全匹配(包括协议、域名、端口),例如前端用http://127.0.0.1:3000时,不能只填http://localhost:3000
  • Security中间件冲突检查:如果strapi::security中间件有额外的CORS规则配置,可能会覆盖当前设置,需确认该中间件未添加冲突的跨域限制

验证配置有效性

发送请求后,在浏览器开发者工具的Network面板中查看响应头:

  • 确认Access-Control-Allow-Origin值为http://localhost:3000而非*
  • 确认响应头包含Access-Control-Allow-Credentials: true

内容的提问来源于stack exchange,提问作者Miguel Ângelo Freitas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:54:59