일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 회고
- JavaScript
- Front-end
- error
- react-query
- swiftUI
- 코딩테스트실력진단
- 코드트리
- 자바스크립트
- 코딩테스트
- velog
- 코드트리챌린지
- git
- Xcode
- UIKit
- frontend
- ios
- tshaped
- SWIFT
- AppleDeveloperAcademy
- Apple Developer Academy
- globalcommunity
- TypeScript
- 알고리즘
- react
- 프로젝트
- NextJs
- iOSDeveloper
- 프론트엔드
- 프로그래머스
Archives
- Today
- Total
Moon Work
[CORS] Cors를 처리해도 Cors 에러가 나는 경우(with Credentials) 본문
끝나지 않는 Cors 에러
서버에 대한 개념도 모를 때 부터 Cors는 나를 괴롭게 하였지만 이렇게 가끔씩 나타나는 이 에러는 등장만으로도 속에서 불이 나곤한다. jwt 토큰을 통한 XSS와 CSRF 공격 방어를 공부하는데 이 녀석을 또 만났는데 cors()를 적용해도 에러가 발생하는 이유를 정리해본다.
에러 코드
Client
axios.defaults.withCredentials = true
axios.post('http://localhost:8080/login', data)
.then(response => ...)
.catch(error => ...)
Server
...
const app = express();
const server = http.createServer(app);
const PORT = 8080;
app.use(cors({
origin: 'http://localhost:3000'
}))
...
문제점
client에서 axios.defaults.withCredentials를 설정해주었다. 이는 client에 있는 쿠키 정보를 server와 공유하기 위함인데 이를 위해서는 client와 server에서 모두 credential에 대한 허용을 해주어야 통신이 가능하다. 따라서 위에서 생긴 에러는 client에서만 Credential에 대해 허용을 해주고 server에서는 허용을 하지 않았기 때문에 발생한 에러이다.
해결
위와 같은 경우에는 cors의 credential option을 설정해줌으로 해결가능하다.
/*
app.use(cors({
origin: "http://localhost:3000"
}))
*/
app.use(cors({
origin: "http://localhost:3000",
credentials: true,
}))
추가: Credential이란
Credential이란 쿠키, Authorization 인증 헤더, TLS client certificated를 포함하는 자격 인증 정보이다. 기본적으로 쿠키는 이 credentioal이 설정되어 있지 않는 한 이런 인증 정보를 포함하여 요청하지 않게 되어 있다. 따라서 이것을 설정해 준다는 것이 쿠키를 서버와 공유한다는 것을 의미한다.
Credential 설정: Client
//방법1
axios.defaults.withCredentials = true
//방법2
axios.post('http://localhost:8080/login',
data,
{withCredentials: true}
)
//방법3
fetch('http://localhost:8080/login', {
method: "POST"
credentials: "include"
})
Credential 설정: Server
//방법1
const httpServer = http.createServer(function(req, res)=> {
response.setHeader('Access-Control-Allow-origin', '*')
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
response.setHeader('Access-Control-Allow-Credentials', 'true')
})
//방법2
axios.use(cors({
origin: '*'
credentil: 'true'
}))
참조
'에러처리' 카테고리의 다른 글
[Git] git merge --no-ff Xcode 에러 해결하기 (0) | 2023.02.04 |
---|---|
[netlify] 호스팅 exit code 1 에러 해결하기 (0) | 2023.01.09 |
에러처리: [eslint] Failed to load plugin 'jsx-a11y' declared in 'package.json (0) | 2022.12.03 |
[Typescript] React props key error (0) | 2022.08.10 |
[React + Typescript] IntrinsicAttributes 에러 (0) | 2022.08.09 |