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

Chrome扩展调用Vercel部署API时遇CORS错误,求修复方案

解决Chrome扩展调用Vercel部署的Next.js API时的CORS错误

问题分析

从错误信息来看,生产环境中API响应未返回Access-Control-Allow-Origin头,导致Chrome扩展的跨域请求被拦截。尽管你配置了多种CORS相关设置,但可能存在配置冲突、路由匹配错误或部署缓存的问题。

具体解决方案

1. 确保API路由的OPTIONS处理正确

将OPTIONS方法与POST方法放在同一个API路由文件中(例如app/api/something/route.ts),确保Vercel生产环境会优先执行该路由内的OPTIONS逻辑,而非默认处理:

export async function OPTIONS(request: Request) {
  const origin = request.headers.get('origin');
  return new NextResponse(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': origin || '*',
      'Access-Control-Allow-Methods': 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
      'Access-Control-Allow-Headers': '*',
    },
  });
}

export async function POST(request: Request) {
  const origin = request.headers.get('origin');
  // 处理你的业务逻辑,生成响应数据
  const data = { /* 响应内容 */ };

  return new NextResponse(JSON.stringify(data), {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': origin || '*',
      'Access-Control-Allow-Methods': 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
      'Access-Control-Allow-Headers': '*',
    },
  });
}

2. 修复全局Headers配置的冲突

你的Next.js全局headers配置中,Access-Control-Allow-Credentials: true与Access-Control-Allow-Origin: *存在冲突——当允许凭证时,Origin不能设为通配符*。如果你的请求不需要凭证(当前fetch代码中未携带),直接删除凭证相关配置:

async headers() {
  return [
    {
      source: "/api/:path*",
      headers: [
        // 移除该行,避免与* Origin冲突
        // { key: "Access-Control-Allow-Credentials", value: "true" },
        { key: "Access-Control-Allow-Origin", value: "*" },
        { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
        { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
      ],
    },
  ];
},

如果后续需要支持凭证,可改为动态校验允许的Origin:

async headers() {
  return [
    {
      source: "/api/:path*",
      headers: [
        { key: "Access-Control-Allow-Credentials", value: "true" },
        { 
          key: "Access-Control-Allow-Origin", 
          value: (req) => {
            // 仅允许指定的Origin访问
            const allowedOrigins = [
              'chrome-extension://pkomeokalhjlopcgnoefibpdabcdefg',
              'http://localhost:3000' // 本地开发环境
            ];
            const origin = req.headers.get('origin');
            return allowedOrigins.includes(origin) ? origin : '*';
          }
        },
        { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
        { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
      ],
    },
  ];
},

3. 删除无用的Rewrites配置

你当前的rewrites配置将/api/something代理到自身域名的同一路径,完全没有意义,直接删除:

// 移除整个rewrites配置
// async rewrites() {
//   return [
//     {
//       source: '/api/something',
//       destination: 'https://abc/api/something',
//     },
//   ];
// },

4. 部署与测试验证

  • 重新部署你的Vercel项目,确保所有配置变更生效。
  • 在Chrome开发者工具的Network面板中勾选「Disable cache」,避免缓存旧的响应头。
  • 用curl测试OPTIONS请求,验证响应头是否正确:
    curl -X OPTIONS https://abc/api/something -H "Origin: chrome-extension://pkomeokalhjlopcgnoefibpdabcdefg" -I
    
    确认返回的响应头包含Access-Control-Allow-Origin且值为你的扩展Origin或*。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:47:32