我已经在一个非常简单的案例上对此进行了测试:
//route.ts
export async function GET() {
return new Response('Hello, Next.js!', {
status: 200,
})
}
我可以通过以下方式称之为罚款:
const response = await fetch(`${API_BASE_URL}generate/test`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}
它返回“Hello, Next.js!”很好。
但是如果我将相同的路由更改为 POST 而不是 GET,例如:
//route.ts
export async function POST() {
return new Response('Hello, Next.js!', {
status: 200,
})
}
并通过以下方式调用:
const response = await fetch(`${API_BASE_URL}generate/test`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: "AA",
}
现在预检请求失败,请求返回405错误;因此,似乎由于某种原因,当我将其更改为 POST 方法时,next.js 不再处理该路由。这是一个错误吗?或者为什么会这样?
我尝试过的一些事情:
即使在最简单的情况下,我也无法让 POST 方法 API 路由处理程序工作。可能是什么问题?
这是我正在使用的解决方案:
在 middleware.ts 中:
export const corsHeaders = {
"Access-Control-Allow-Origin": "http://localhost:19006",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
export async function middleware(request: NextRequest) {
const response = NextResponse.next()
// Need to handle OPTIONS request here, unless you want to not use middleware
// In which case you can define the OPTIONS method and set the CORS headers within route.ts
// But using middleware is nice to avoid boilerplate of setting CORS on each route
if (request.method === 'OPTIONS') {
return NextResponse.json({}, {headers: corsHeaders})
}
// Then here set the CORS headers that will be returned with the regular response
response.headers.append("Access-Control-Allow-Origin", corsHeaders['Access-Control-Allow-Origin'])
response.headers.append("Access-Control-Allow-Methods", corsHeaders['Access-Control-Allow-Methods'])
response.headers.append("Access-Control-Allow-Headers", corsHeaders['Access-Control-Allow-Headers'])
// Continue to eventually call the matching route.ts method
return response;
}
令人困惑的值得注意的问题是:GET 和 POST 请求的处理方式与 CORS 相同,因此我的测试存在缺陷。并且您必须在 OPTIONS 请求上设置 CORS 标头(如果没有在每个 Route.ts 中定义 OPTIONS,则提前返回)以及正常请求。感谢菲尔帮助我解决这个问题。