Minwook’s portfolio

HTTP header CORS 설정 본문

Today I Learned

HTTP header CORS 설정

yiminwook 2022. 8. 27. 21:24

 

 

HTTP header

 

Access-Control-Allow-Origin

 

 서버에서 특정 Origin으로부터의 요청을 허용할지에 대해서 나타냅니다.

Access-Control-Allow-Origin: *                           //모든 Origin에 대한 요청을 허용
Access-Control-Allow-Origin: "https://localhost:3000"    //해당 Origin에만 접근할 수 있도록 허용함

 

Origin을 *로 모든 요청으로 허용시킬 경우 보안상 문제가 될 수 있습니다.

 

*same origin이란?  protocol과 Host, Port 3가지가 동일한 Origin

 

 


 

 

Access-Control-Allow-Methods

 

응답으로 허용할 HTTP Method를 지정합니다.

Access-Control-Allow-Methods: *
Access-Control-Allow-Methods: "GET", "POST", "OPTIONS"....

 

 


 

 

Access-Control-Allow-Credentials

 

credentials 옵션은 브라우저가 요청(req)에 인증에 관련된 정보(쿠키)를 담을 수 있게 해주는 옵션

fetch API에서의 credentials 옵션
same-origin (기본값) 같은 출처 간 요청에만 인증 정보를 담을 수 있다
include 모든 요청에 인증 정보를 담을 수 있다
omit 모든 요청에 인증 정보를 담지 않는다

 

 

 

서버에서도 응답 header에 Access-Control-Allow-Credentials 설정을 해야합니다.

false로 설정하거나 생략시에는 Credential 요청을 처리할 수 없습니다.

 

또한 Credentials 옵션을 same-origin 또는 include로 요청(request)할시에는

Allow-Origin에는 *를 사용할 수 없고 Origin을 명시해야합니다.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

Access-Control-Allow-Credentials: true

 

 


 

 

예시코드

 

Client

//import React from 'react';
//import axios from 'axios';

//axios.defaults.withCredentials = true  모든 요청을 true로 설정도 가능

axios({
        method: "GET",
        url: 'https://localhost:3000',
        headers: { "Content-Type": 'application/json' },
        withCredentials: true,  //fetch API에서는 include, axios에서는 true
      });

 

Server

//const express = require("express");
//const cors = require("cors");
//const app = express();

app.use(
  cors({
    origin: ["https://localhost:3000"],    //*은 사용불가 
    methods: ["GET", "POST", "OPTIONS"],
    credentials: true
  })
);

 

 


 

 

참고

https://developer.mozilla.org/ko/docs/Web/HTTP/CORS

https://evan-moon.github.io/2020/05/21/about-cors/

https://www.inflearn.com/blogs/1487

https://inpa.tistory.com/entry/WEB-%F0%9F%93%9A-CORS-%F0%9F%92%AF-%EC%A0%95%EB%A6%AC-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95-%F0%9F%91%8F

https://velog.io/@logqwerty/CORS

 

 

 

 

'Today I Learned' 카테고리의 다른 글

Hashtable 정리  (0) 2022.12.28
배열(Array) 정리  (0) 2022.12.26
시간복잡도, Big O 표기법  (1) 2022.12.26
Express에서 next()의 기능분석 및 에러처리방법  (0) 2022.10.17
node version 관리 및 npm install option  (0) 2022.08.31
Comments