일상생활
NextJS를 API로만 이용할때 CORS 에러 대처 방법
WebHack
2023. 8. 8. 10:56
파일명은 middleware.ts으로 사용되야 하고 위치는 루트(/) 위치 즉 package.json 파일 위치와 같아야 한다.
import { NextResponse } from "next/server";
// the list of all allowed origins
const allowedOrigins = [
'http://localhost:3011',
];
export function middleware(req: any) {
// retrieve the current response
const res = NextResponse.next()
// retrieve the HTTP "Origin" header
// from the incoming request
let origin = req.headers.get("origin")
// if the origin is an allowed one,
// add it to the 'Access-Control-Allow-Origin' header
if (allowedOrigins.includes(origin)) {
res.headers.append('Access-Control-Allow-Origin', origin);
}
// add the remaining CORS headers to the response
res.headers.append('Access-Control-Allow-Credentials', "true")
res.headers.append('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT,OPTIONS')
res.headers.append('Access-Control-Allow-Headers', 'Origin, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization')
return res
}
// specify the path regex to apply the middleware to
export const config = {
matcher: '/api/:path*',
}
|