我在发布到 api 路由时遇到 CORS 错误。我的 next.config.mjs 如下所示:
const nextConfig = {
async headers() {
return [
{
// matching all API routes
source: '/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ 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' }
]
}
]
}
}
我的 app/path/route.ts 看起来像这样:
export async function POST() {
// .....
return NextResponse.json({ status: 'ok' })
}
事实证明,路由上还需要 GET 处理程序才能使预检请求正常工作,在将 GET 方法添加到我的路由后,CORS 错误消失了。
export async function POST() {
// .....
return NextResponse.json({ status: 'ok' })
}
// GET just to return 200 status for preflight to work
export async function GET() {
return NextResponse.json({ status: 'ok' })
}