일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- ubuntu
- https
- Load Balancer
- 조건문
- 노마드코더
- 메소드
- Node.js
- it
- nomadcoder
- CORS
- JWT
- npm
- 자바스크립트
- JavaScript
- Nodejs
- elb
- 생활코딩
- AWS
- reduce
- mongodb
- 프로그래머스
- 항해99
- Joi
- 타입스크립트
- TypeScript
- MYSQL
- nginx
- wil
- mongoose
- java
- Today
- Total
V-logue
[Node.js] Express.cors 본문
https://surprisecomputer.tistory.com/32
[Node.js] express cors 사용하기
1. 서론 리버스 프록시 서버로 NGINX를 두고 한 워크스테이션에서 Swagger와 node.js 서버를 함께 구동한 적이 있다. Swagger의 포트를 8085로 지정하고 node.js 서버는 443번으로 지정했는 데, CORS 에러가 발
surprisecomputer.tistory.com
CORS(Cross-Origin Resource Sharing)란
자신이 속하지 않은 다른 도메인, 다른 프로토콜, 혹은 다른 포트에 있는
리소스를 요청하는 cross-origin HTTP 요청 방식이다.
cross-origin HTTP 요청 방식에 대해서는 mozilla 사이트의 다음의 그림을 보면 좀 더 이해가 쉽다.
서버는 Cors에 대해서 기본적으로 제한을 두고 있는데, 특정 서버 리소스에 임의의 웹사이트에서
request를 보낼 수 있다면 악의적으로 세션을 탈취하거나 문제를 일으킬 수 있어서라고 한다.
사용법은 다음과 같다.
먼저 모두에게 허용하는 법
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
위와 같이 별도의 처리 없이, app.use(cors())하게 된다면
모든 도메인에서 제한 없이 해당 서버에 요청하고 응답을 받을 수 있게 된다.
다음으로는,
특정 도메인에게만 허용하는 법
const http = require('http');
const express = require('express');
const app = express();
const server = createServer(app);
const cors = require('cors');
const PORT = 8080;
let corsOptions = {
origin: 'https://www.domain.com',
credentials: true
}
app.use(cors(corsOptions));
app.get('/', (req, res) => {
res.send('Hello, World!');
});
server.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});
위와 같이 corsOptions 변수에 허용할 도메인을 추가하고, app.use(cors(corsOptions));를 넣어주게 되면,
해당 corsOptions의 origin값인 해당 도메인은 제한 없이 서버에 요청하고 응답할 수 있게 된다.
참고
https://www.npmjs.com/package/cors
cors
Node.js CORS middleware. Latest version: 2.8.5, last published: 4 years ago. Start using cors in your project by running `npm i cors`. There are 10462 other projects in the npm registry using cors.
www.npmjs.com
*추가적인 사항이 있다면, 추가
'발자취 > Node.js' 카테고리의 다른 글
[Node.js] Kakao 소셜로그인 구현 (0) | 2022.06.21 |
---|---|
[Node.js] Express.multer, Multer-S3 (0) | 2022.06.13 |
[Node.js] Express.joi 모듈을 활용해 validation을 검증하자 (0) | 2022.06.09 |
[Node.js] bcrpyt 모듈, (0) | 2022.06.09 |
[Node.js] JavaScript에서 Morgan과 Winston을 사용해 ExpressJS를 위한 더 나은 logs system (0) | 2022.06.08 |