ExpressJS CORS(Cross-Origin-Resource-Sharing)
클라이언트(브라우저)의 요청 도메인과 응답 받는 서버 도메인이 다를 경우 브라우저가 발생시키는 에러
- 웹 개발자라면 무조건 보게되는 에러(앱은 웹뷰 사용 시 CORS 에러 발생)
- 클라이언트(서버)에서 서버로 요청 보낼 경우는 발생하지 않음
- 브라우저에서 발생 시키는 문제지만 응답을 보내주는 서버에서 처리해야 함
- 서버 응답(Response Headers)에 Access-Control-Allow-Origin을 넣어주면 해결 가능(req.setHeaders)
cors 설치
- cors 모듈
전역 라우터 설정
- cors 메서드 사용
- origin: 요청 허용 할 도메인 모두("*") 여러개면 배열로 ["http:localhost:2000", "http://localhost:2001"]
- credentials: 서버와 클라이언트간의 쿠키 공유 여부
클라이언트(axios)에서도 withCredentials: true를 해줘야 함
- req.get("origin"): 요청 헤더에 origin 속성 가져옴
const express = require("express");
const cors = require("cors");
const router = express.Router();
router.use(async (req, res, next) => {
const domain = await Domain.findOne({
where: { host: url.parse(req.get("origin")).host },
})
if (domain) {
cors({
origin: req.get("origin"),
credentials: true,
})(req, res, next);
} else {
next();
}
});
'서버 > Express' 카테고리의 다른 글
ExpressJS Sequelize transaction (0) | 2022.06.17 |
---|---|
ExpressJS MySQL CRUD (0) | 2022.05.14 |
ExpressJS JWT (0) | 2022.03.26 |
ExpressJS method-override (0) | 2022.03.22 |
ExpressJS middleware (0) | 2022.01.22 |