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

Next.js App Router中POST请求API路由出现CORS错误排查

问题分析与解决方案

核心问题点

  • CORS配置冲突:你同时设置了Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: *,这违反了CORS规范。当允许携带凭证(如Cookie、HTTP认证信息)时,Access-Control-Allow-Origin不能使用通配符*,必须指定具体的请求源。
  • 未处理OPTIONS预请求:浏览器发送POST这类非简单请求前,会先发送OPTIONS预请求验证跨域权限。你的API路由仅实现了POST方法,未处理OPTIONS请求,可能导致预请求失败触发CORS错误。

修正步骤

1. 调整CORS配置

修改next.config.mjs,将Access-Control-Allow-Origin改为具体域名,或根据请求动态匹配合法源:

固定单源版本

const nextConfig = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          // 替换为你的前端实际域名,比如本地开发用http://localhost:3000
          { key: 'Access-Control-Allow-Origin', value: 'https://your-frontend-domain.com' }, 
          { key: 'Access-Control-Allow-Methods', value: 'GET,DELETE,PATCH,POST,PUT' },
          { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Authorization, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' }
        ]
      }
    ]
  }
}

export default nextConfig;

多源动态匹配版本

// 配置允许的前端源列表
const allowedOrigins = ['https://your-frontend-domain.com', 'http://localhost:3000'];

const nextConfig = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: async ({ req }) => {
          const origin = req.headers.get('origin');
          // 匹配合法源,无匹配则用默认值
          const allowedOrigin = allowedOrigins.includes(origin) ? origin : 'https://your-frontend-domain.com';
          return [
            { key: 'Access-Control-Allow-Credentials', value: 'true' },
            { key: 'Access-Control-Allow-Origin', value: allowedOrigin },
            { key: 'Access-Control-Allow-Methods', value: 'GET,DELETE,PATCH,POST,PUT' },
            { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Authorization, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' }
          ];
        },
      },
    ];
  },
};

export default nextConfig;

2. 处理OPTIONS预请求

在app/path/route.ts中添加OPTIONS方法处理,确保预请求能正常响应:

import { NextResponse } from 'next/server';

export async function POST() {
  // 你的业务逻辑代码
  return NextResponse.json({ status: 'ok' });
}

// 处理OPTIONS预请求
export async function OPTIONS() {
  return NextResponse.json({}, {
    headers: {
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Origin': 'https://your-frontend-domain.com', // 与config配置保持一致
      'Access-Control-Allow-Methods': 'GET,DELETE,PATCH,POST,PUT',
      'Access-Control-Allow-Headers': 'X-CSRF-Token, X-Requested-With, Authorization, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
    },
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:22:55