[Inflearn][JohnAhn] 노드 리액트 기초 (21~22)

ann·2023년 11월 7일
0

#21

  • 지금까지는 request를 할 때 client 부분이 없었기 때문에 POSTMAN을 이용했다.
  • 하지만 이제는 client가 있으니 React JS 부분에서 request를 보내면 된다.
  • 그때 사용할 것은 AXIOS인데, jQuery를 사용할 때의 AJAX라고 보면 된다.
  • client 디레터리로 이동해서 npm install axios --save 설치

  • useEffect, axios

    client/src/components/views/LandingPage/LandingPage.sj====
    import React, { useEffect } from 'react'
    import axios from 'axios';
    
    function LandingPage() {
    
      useEffect(() => {
        // client는 3000에서 보내는데 server는 5000이기 때문
        axios.get('http://localhost:5000/api/axiostesting')
        .then(response => console.log(response.data))
      }, [])
      
      return (
        <div>LandingPage</div>
      )
    }
    
    export default LandingPage
    server/index.js===============================================================
    app.get('/api/axiostesting', (req, res) => {res.send('AXIOS testing success')})
  • root 디렉터리에서 npm run backend를 하고, client 디렉터리에서 npm run start를 해야하는데, 오류가 날 것이다.

  • 그런데 일단 npm run backend하기 전에 루트 디렉터리에 있는 package.json의 backend 스크립트에서 경로를 index.js에서 server/index.js로 바꿔주어야 한다.

  • 22장에서 이어서 오류 해결할 것이다.

#22

  • Cors 정책 때문에 발생하는 문제를 해결해야한다.

  • 방법은 여러가지이지만 우리는 Proxy로 해결할 것이다.

  • 여기로 들어가서 문서 참고

  • clinet에서 npm install http-proxy-middleware --save 설치

  • server 폴더에 setupProxy.js 파일 생성 후 문서 참고해서 다음내용 작성

    // https://create-react-app.dev/docs/proxying-api-requests-in-development 참고
    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use(
        '/api',
        createProxyMiddleware({
          // 프론트에서 서버로 타겟을 줄 때 5000으로 바꿔서 주겠다는 의미
          target: 'http://localhost:5000',
          changeOrigin: true,
        })
      );
    };
  • LandingPage.js의 get url을 http~ 삭제하고 /api/axios만 남겨두기

0개의 댓글