1. package.json

package.json에서 proxy를 하나만 설정할 수 있고, 여러개 설정할 수도 있다.

http-proxy-middleware 로 설정하기! CRA(Create-React-App) v2 부터 변경됨

StackOverflow

// 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://velog.io/@tw4204/React-%EA%B0%9C%EB%B0%9C%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C%EC%9D%98-CORS%EB%A5%BC-%EC%9C%84%ED%95%9C-proxy-%EC%84%A4%EC%A0%95

https://github.com/chimurai/http-proxy-middleware

 

 

+ Recent posts