JavaScript & Node js

[node.js/react] server와 client간의 port가 달라 연결이 안될 때

피곤핑 2020. 7. 1. 12:08

Server - Client 간 다른 포트를 가지고 있으면 아무런 설정 없이 Request 를 보낼 수 없음.

-> Cors(cross-origin resource sharing) 이라는 정책때문인데! (보안) 

이를 해결하려면 여러 방법이 있지만 서버와 클라이언트 둘다 만족시키면서 유연하게 할 수 있는 것이 바로 Proxy!

 

https://create-react-app.dev/docs/proxying-api-requests-in-development

 

Create React App · Set up a modern web app by running one command.

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

create-react-app.dev

위 링크에서 

 

# Configuring the Proxy Manually 부분부터 보면 된다!

 

$ npm install http-proxy-middleward --save

 

설치 한 뒤

client (react로 만든 폴더안) 안의 src 디렉토리 안에 setupProxy.js 파일을 만들고

 

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

 

 

위의 코드를 붙여 넣어준다.

target 안에 있는 포트에 서버에서 사용하는 포트를 넣어주면 된다!

그리고 본래 LandingPage.js 안 axios.get 안에 아래와 같이 포트를 넣어주었었는데 이를 지워야 한다.

 

- LandingPage.js (전)

import React, { useEffect } from 'react'
import axios from 'axios';

function LandingPage(){

    useEffect(() => {
        axios.get('http://localhost:5000/api/hello')
        .then(response => console.log(response.data))
    }, [])
       
    return(
        <div>
            LandingPage
        </div>
    )
}

export default LandingPage

 

- LandingPage.js (후)

import React, { useEffect } from 'react'
import axios from 'axios';

function LandingPage(){

    useEffect(() => {
        axios.get('/api/hello')
        .then(response => console.log(response.data))
    }, [])
       
    return(
        <div>
            LandingPage
        </div>
    )
}

export default LandingPage