Next.js 13.4.4 POST请求CORS错误的解决方法
解决Next.js 13.4.4跨域调用/logout接口的CORS错误
问题情况
我使用Next.js 13.4.4搭建服务,配置了http://localhost:5000/logout接口,对应的src/app/logout/route.tsx代码如下:
import { NextRequest, NextResponse } from "next/server"; export async function POST(req: NextRequest) { return new NextResponse("POST: /logout"); }
当从运行在http://localhost:3000的另一个应用调用该接口时,持续触发CORS错误:
Access to XMLHttpRequest at 'http://localhost:5000/logout' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
调用接口的fetch代码如下:
const response = await fetch('http://localhost:5000/logout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', });
解决方法
在route.tsx中手动添加OPTIONS方法并配置CORS响应头,即可修复该错误:
export async function OPTIONS(request: NextRequest) { 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': 'Content-Type, Authorization' } }) }
原理:跨域POST请求会先发送OPTIONS预请求做权限校验,Next.js默认不会处理这类预请求,因此需要手动实现OPTIONS方法,返回包含CORS允许规则的响应头,让预请求通过校验后,后续的POST请求才能正常执行。
内容的提问来源于stack exchange,提问作者hantoren
相关产品推荐
相关产品推荐

