on
[React] Axios 및 Proxy 설정
[React] Axios 및 Proxy 설정
Axios란?
Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.
백엔드 및 프론트엔드에서 통신을 쉽게하기 위해 Ajax와 함께 사용된다.
사용법 및 예제는 아래 공식문서를 참고하면 된다.
https://axios-http.com/docs/intro
npm install axios --save
먼저 axios 패키지를 설치해준다.
// client/src/components/views/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 ( LandingPage ) } export default LandingPage
다음과 같이 axios 객체를 이용하여 간단하게 HTTP 요청을 보낼 수 있다.
// server/index.js app.get('/api/hello', (req, res) => { res.send("안녕하세요~"); })
서버측에서도 요청을 받기위해 다음과 같이 추가해주었다.
사용자의 서버 포트는 5000번이고 클라이언트 포트는 3000번이기 때문에 이대로 사용한다면 에러가 난다.
useEffect(() => { axios.get('http://localhost:5000/api/hello') .then(response => console.log(response.data)) }, [])
이를 해결하기 위해 5000번으로 요청을 보내도 여전히 에러가 난다.
이는 CORS 정책 때문이다. 외부에서 요청을 보내면 보안상의 이슈가 있을 수 있기 때문에 CORS 정책이 필요하다.
(CORS란? : Cross-Origin Resource Sharing의 약자로 서로 다른 Origin 사이에서 자원을 공유할 때 사용되는 정책)
Proxy로 CORS 해결
CORS를 해결하기 위해서 proxy 서버를 이용하는 방법을 사용하였다.
https://create-react-app.dev/docs/proxying-api-requests-in-development/
npm install http-proxy-middleware --save
먼저 http-proxy-middleware 를 설치해준다.
// client/src/setupProxy.js const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true, }) ); };
proxy 설정을 추가해줌으로 /api로 시작되는 API는 target으로 설정된 서버 URL로 호출하도록 설정된다.
changeOrigin 설정은 대상 서버 구성에 따라 호스트 헤더가 변경되도록 설정해주는 옵션이다.
from http://anjuna.tistory.com/61 by ccl(A) rewrite - 2021-10-27 02:27:15