피곤핑
코딩일탈
피곤핑
전체 방문자
오늘
어제
  • 분류 전체보기
    • Kotlin & Java
    • Spring
      • Spring Security
      • Spring
    • 네트워크
    • JavaScript & Node js
    • Docker
    • Python3
    • Unity
    • 딥러닝
    • 객체지향프로그래밍
    • Error 보고서
    • 나의 이야기 & 회고
    • HTML & CSS
    • Archive
    • 독서

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 99클럽
  • Client
  • 코딩테스트준비
  • JavaScript
  • nodejs
  • 항해99
  • TiL
  • 개발자취업
  • 오블완
  • 티스토리챌린지

최근 댓글

hELLO · Designed By 정상우.
피곤핑

코딩일탈

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

 

'JavaScript & Node js' 카테고리의 다른 글

[nest.js] AWS s3 bucket 에 파일 여러개 업로드 + rest api 만들기  (2) 2021.10.26
npm ERR! must provide string spec  (0) 2021.07.13
[JavaScript] 정규표현식 (Regular Expression)  (0) 2020.07.07
[Redux] 노드 리액트 Redux 기본 구조 만들기!  (0) 2020.07.01
[Concurrently] 서버와 클라이언트 동시에 실행시키기!  (0) 2020.07.01
    'JavaScript & Node js' 카테고리의 다른 글
    • npm ERR! must provide string spec
    • [JavaScript] 정규표현식 (Regular Expression)
    • [Redux] 노드 리액트 Redux 기본 구조 만들기!
    • [Concurrently] 서버와 클라이언트 동시에 실행시키기!
    피곤핑
    피곤핑

    티스토리툴바