NextJS写的接口允许跨域访问

之前是采用middleware的方式,现在新版本的不适用了 …

重点就是想办法给response添加允许跨域的请求头 …

Snipaste 2024 11 10 23 46 07

  1. allowCorsHeaders.ts
export default {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
  1. OPTIONS请求返回204
export async function OPTIONS(request: NextRequest) {
return NextResponse.json({}, { headers: allowCorsHeaders, status: 204 });
}
  1. GET响应的时候,添加allowCorsHeaders
/**
* http://localhost:3000/api/testMongo
* @param reqest
* @returns
*/
export async function GET(request: NextRequest) {
let params = request.nextUrl.searchParams;
let current = parseInt(params.get("current") ?? `1`);
let pageSize = parseInt(params.get("pageSize") ?? `10`);
// 计算分页的跳过数量
const skip = (current - 1) * pageSize;
const db = client.db("sample_mflix");
const total = await db.collection("movies").countDocuments();
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.skip(skip)
.limit(pageSize)
.toArray();
return NextResponse.json(
{
current,
pageSize,
success: true,
total,
data: movies,
env: process.env.ENV,
},
{ headers: allowCorsHeaders }
);
}

NextJS写的接口允许跨域访问

https://cctv3.net/static/20241110/next-api-cors.html

作者

陈桥驿站

发布于

2024-11-10

更新于

2024-11-26

许可协议

评论