之前是采用middleware
的方式,现在新版本的不适用了 …
重点就是想办法给response
添加允许跨域的请求头 …
allowCorsHeaders.ts
export default { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", };
|
OPTIONS
请求返回204
export async function OPTIONS(request: NextRequest) { return NextResponse.json({}, { headers: allowCorsHeaders, status: 204 }); }
|
GET
响应的时候,添加allowCorsHeaders
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 } ); }
|