본문 바로가기
HTTP

React <-> Node.js CORS 이슈

by 안자바먹지 2020. 12. 17.
728x90

한 프로젝트 안에서 클라이언트(react)와 서버(node.js) 분리되어 있고, 클라이언트에서 axios를 사용해 서버로 요청을 보냈을 때 CORS 에러가 발생했다.

 

 

이때 서버의 포트는 5000번이고, 클라이언트의 포트는 3000번이다. 이렇게 두 개의 포트가 다르다면 CORS 정책에 의해 별도의 설정 없이는 요청을 보낼 수 없다. 

 

이것을 해결하는 방식은 여러가지가 있는데, 대표적으로 Proxy를 사용해서 해결할 수 있다.

 

create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually

 

Proxying API Requests in Development | Create React App

Note: this feature is available with react-scripts@0.2.3 and higher.

create-react-app.dev

 

 

해당 사이트에 친절하게 방법이 나와있다. 

 

1. 클라이언트 쪽에 설치해준다.  npm install http-proxy-middleware --save

2. src/setupProxy.js 파일을 만들어서 아래와 같이 작성한다. 

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

3. 이후 다시 확인해 보면 정상적으로 request를 보내고 response를 받은 것을 볼 수 있다.

728x90

댓글