다른 엔트포인트에 CORS설정하기

HARIBO·2021년 11월 22일
0

다른 엔트포인트에 CORS설정하기

  • preflight가 발생하는 경우, cors패키지의 레퍼런스 코드는 아래와 같다.
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

//아래와 같이 모든 options요청에 대해 허용하는 방법도 있다.
//app.options('*', cors()) // include before other routes
  • 만약 클라이언트와 서버가 같은 쿠키를 사용하고 싶을 경우, withCredentials 속성을 'true'로 사용하게 된다.
// 클라이언트
//axios를 사용해 post요청
axios.post('https://localhost:4000/users/login',
        <body>,
        { 'Content-Type': 'application/json', withCredentials: true })


//서버(express router사용)
router.options('/login', cors({origin: 'https://localhost:3000', credentials: true}));
router.post('/login',cors({origin: 'https://localhost:3000',
credentials: true}), <콜백 함수>);
  • 주의할 점은 credentials에 'true'값을 주게 될 경우, origin을 지정하지 않거나 와일드카드를 사용하면 아래와 같은 오류가 발생한다.

0개의 댓글