express cors문제 해결

YEONGHUN KO·2023년 8월 31일
0

BACKEND - EXPRESS

목록 보기
2/3
post-thumbnail

express에서 서버를 세팅하고 client에서 요청을 보냈는데 cors에러가 떴다.

찾아보니 역시나 express에서 요청이 들어오는 쪽 origin과 요청의 종류를 명시해야한다. 만약 요청에 cookie, http 인증같은 보안 인증 정보를 포함해 주고받으려면 양쪽에서 credentials을 허용해야한다.

server

// index.ts

app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
    credentials: true,
  })
);

만약 cors 라이브러리가 아닌 수동으로 하고 싶으면 아래와 같이 설정

// index.ts
app.use((req, res, next) => {
  const allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
       res.setHeader('Access-Control-Allow-Origin', origin);
  }
  //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', true);
  return next();
});

응답 헤더를 직접설정하면 됨 ㅎㅎ

client

// api.ts
export const client = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
});
profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글