Study/React
[React] Proxy 여러 개 설정하기
성으니:)
2023. 5. 3. 14:48
1. package.json
package.json에서 proxy를 하나만 설정할 수 있고, 여러개 설정할 수도 있다.
http-proxy-middleware 로 설정하기! → CRA(Create-React-App) v2 부터 변경됨
// proxy 단일 설정
{
// ...
"proxy": "http://localhost:8000"
}
{
...
"proxy": {
"/api": {
"target": "http://localhost:8000"
},
"/auth": {
"target": "http://localhost:8080"
}
}
}
// http://localhost:3000/api/posts => http://localhost:8000/api/posts
// http://localhost:3000/auth/login => http://localhost:8080/auth/login
2. http-proxy-middleware
설치
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
적용1
// src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
적용2
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = (app) => {
app.use(
createProxyMiddleware(
['/v1', '/v2'],
{
target: process.env.REACT_APP_API_URL,
changeOrigin: true,
router: {
'/v2': process.env.REACT_APP_V2_URL
},
pathRewrite: {
'^/v2': ''
}
}
)
);
}
참고 사이트
https://velog.io/@eunnbi/Project-cra-proxy-setting
https://serpiko.tistory.com/883
https://freestrokes.tistory.com/164
https://velog.io/@thovy/TROUBLESHOOTING-Set-up-a-proxy-and-set-up-multiple-proxies
https://evan-moon.github.io/2020/05/21/about-cors/
https://github.com/chimurai/http-proxy-middleware