본문 바로가기
Back-End/Express

[Express] CORS Configuration Options

by SeanK 2021. 12. 27.

오늘 Express 코드를 만지다가 CORS를 설정해야 하는 상황이 있었다. 

 

분명 공부했는데...

 

분명 알고있는 개념인데...

 

왜 기억이 하나도 나지 않는 걸까...

 

인생...

 

그래서 오늘은 힘들게 CORS의 옵션들에 대해 알아보자. 

 

 

Simple Usage

 

우선은 가장 기본적인 Simple Usage. 즉 모든 CORS 요청을 허용한다는 의미의 코드이다. 

 

app.use(cors())

 

아마, 'CORS를 설정하라'라는 말에 뇌절이 온 이유는 아마 내가 위 코드만 주야장천 사용했기 때문이다. 

 

Single Usage

 

뿐만 아니라 단 하나의 라우팅에서만 CORS를 허용하는 방법도 있다. 

 

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

 

요렇게, 메소드 안에 cors()를 파라미터로 넣으면 해당 메서드에서만 CORS가 허용되게 된다. 

 

Configuring CORS

자, 이제 본격적으로 CORS를 세세하게 설정하는 방법에 대해 알아보자. 

 

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

 

우선 위와같이 cors() 메서드에 인자로 옵션 객체를 설정하여 넣게 되면, 

 

필자가 원했던 CORS 설정을 할 수 있게 된다. 

 

Option으로는 여러개가 있는데 공식 문서에는 아래와 같이 설명되어 있다. 

 

  • origin: Configures the Access-Control-Allow-Origin CORS header. Possible values:
    • Boolean / String / RegExp / Array / Function
  • methods: Configures the Access-Control-Allow-Methods CORS header. Expects a comma-delimited string (ex: ‘GET,PUT,POST’) or an array (ex: ['GET', 'PUT', 'POST']).
  • allowedHeaders: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (ex: ‘Content-Type,Authorization’) or an array (ex: ['Content-Type', 'Authorization']). If not specified, defaults to reflecting the headers specified in the request’s Access-Control-Request-Headers header.
  • exposedHeaders: Configures the Access-Control-Expose-Headers CORS header. Expects a comma-delimited string (ex: ‘Content-Range,X-Content-Range’) or an array (ex: ['Content-Range', 'X-Content-Range']). If not specified, no custom headers are exposed.
  • credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.
  • maxAge: Configures the Access-Control-Max-Age CORS header. Set to an integer to pass the header, otherwise it is omitted.
  • preflightContinue: Pass the CORS preflight response to the next handler.
  • optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.

 

음... 이해하기 어려우니 하나씩 알아보자. 

 

ORIGIN

요청을 허용할 출처를 적는 옵션이다. 보통 "www.swimmingindev.tstory.com" 과 같이 CORS를 허용할 주소를 넣는다. *는 와일드카드로 모든 주소로부터의 CORS를 허용한다는 뜻이다. 

 

Methods

methods는 간단하다. 의미에서 유추할 수 있듯이 get, post 등 어떤 호출을 허용할 것인지 설정한다. 

 

AllowedHeaders

allowedHeaders란 preflight 요청에서 추후에 어떤 HTTP 헤더가 사용될지 알려주는 역할을 한다. 즉 어떤 헤더들을 허용할 것인가에 대한 명세이다. ['Content-Type', 'Authorization'] 등과 같이 value를 적는다. 

 

ExposedHearders

exposedHeaders는 브라우저 상에서 스크립트로 노출되는 헤더의 목록을 알려주기 위해 사용된다. 

 

Credentials

Credentials는 브라우저에게 response를 프론트엔드프런트엔드 자바스크립트 코드로 노출시킬지를 알려준다. 만약 credential mode가 include이면서 동시에 credentials를 true로 설정하면 브라우저는 프런트엔드 자바스크립트에 응답을 노출시킨다.