본문 바로가기
Web/React Node js

리액트 기초 강의 (3) - 데이터 Flow & Axios

by SeleniumBindingProtein 2022. 3. 1.
728x90
반응형

 - server : node.js

 - client : react.js

 - data base : mongoDB

 - client 부분이 없어서 포스트맨을 사용하였는데, axios를 설치하여 client 안에서 요청을 보내려고 함

 npm install axios --save

 - client/component/views/LadingPage/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;

 

 - server/index.js 

 - 엔드포인트를 api/hello로 설정하여 만들어 놓은 서버의 index.js에서 확인

app.get('/api/hello', (req,res) => {
    res.send('안녕하세요~ ')
})

 - server 실행

npm run backend

 - client 실행

cd client

npm run start

 => 실행은 되었지만, server 포트는 6660이고, client 포트는 3000이라서 오류가 뜨는 것

 

** 몽고 디비 에러 

  => Network Access 에서 IP를 pending 해줘야 함

 

 - Proxy를 통해 포트 오류 해결

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

 

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

cd client
npm install http-proxy-middleware --save

 - src/setupProxy.js 파일 생성 후 아래 코드 추가 

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

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

[결과 출력]

728x90
반응형

댓글