JS/React
📚 [React] 리액트 프록시 설정 (Proxy)
Nyanggu
2023. 1. 26. 16:33
클라이언트 호스트와 서버 호스트가 다를때!
CORS정책때문에!!
두개의 다른 포트를 가지고 있는 서버는 아무 설정없이 리퀘리스트를 보낼 수 없음
해결방법은 여러방법 중 Proxy를 사용하는 방법이 있다!!!!!
먼저 나의 서버의 호스트는 8080, 클라이언트 호스트는 3000이다.
client > src > components > views > LandingPage > LandingPage.js 에
/api/hello로 요청을 보내고 요청을 받았다면 콘솔에 받은 데이터를 출력해달라고 한다.
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생성
app.get("/api/hello", (req, res) => {
res.send("하이~~~~~~~");
});
여기까지만 진행했을땐 콘솔엔 CORS오류가 확인된다.
해결을 위해서 아래 프록시 설정을 해주자
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
프론트단에서 아래 npm을 설치한다.
npm install http-proxy-middleware --save
기존 scr폴더에 setupProxy.js 파일을 생성해주고, 아래 내용을 복붙해준다.
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware({
target: "http://localhost:8080",
changeOrigin: true,
})
);
};
이렇게만 해주면 오류 없이 작동한다