React setupProxy

울고있는따개비·2024년 7월 17일
0

study

목록 보기
11/11
post-thumbnail

proxy 수동 설정(setupProxy)

서버와 클라이언트가 통신할 때 CORS 헤더를 통해 통신을 진행하는데 통신을 주고받는 통신 주체들의 도메인, 프로토콜, 포트가 일치하지 않으면 CORS 에러가 발생한다.
서버와 클라이언트 사이에 중계기로서 대리로 통신을 수행하게 하는 프록시 서버를 설정하면 CORS 에러를 해결할 수 있다.

proxy 수동 설정 방법

package.json을 통한 설정

 "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "통신할 서버 주소"

http-proxy-middleware setupProxy.js를 통한 설정

npm http-proxy-middleware
https://www.npmjs.com/package/http-proxy-middleware

npm install --save-dev http-proxy-middleware // npm 사용 일 경우
yarn add http-proxy-middleware // yarn 사용 일 경우

setupProxy.js 파일을 src 밑에 생성 후 아래와 같이 프로젝트 proxy 설정을 커스터마이징
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org(통신할 서버 주소)',
  changeOrigin: true,
});

// 'apiProxy' is now ready to be used as middleware in a server.
  • target은 protocol + host. 해당 어플리케이션에서 /api로 시작되는 endpoint(API가 서버에서 리소스에 접근할 수 있도록 가능하게 하는 URL)가 서버에 어떠한 통신을 요청한 경우, proxy 서버가 중계 역할을 하며 target으로 지정한 '통신할 서버 주소'로 통신하면서 서버를 우회하게 된다.
    예시) 위 설정을 통해서 axios나 fetch로 요청 시에 /posts/1로 호출하게 되면
    통신할 서버 주소/posts/1 로 호출하게 된다.

  • changeOrigin 설정은 http-proxy 모듈의 설명과 같이 대상 서버 구성에 따라 호스트 헤더가 변경되도록 설정하여 준다.

  • pathRewrite는 서버 API라고 가정했을 때 프론트엔드에서 호출 시 API에 특정 URL 규칙을 만들어 가독성을 높이고 싶거나 다수의 proxy를 추가해야 할 업무상 프로세스가 존재할 경우, 화면에서 API URL path를 대체해주는 역할을 한다. 객체 키는 정규식으로 작성한다.

아래와 같이 설정할 경우 axios나 fetch 설정 시 /api/posts/1로 호출하게 되면 api는 ''공백으로 대체되어 호출하게 된다.

// src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(
        createProxyMiddleware('/api', {
            target: '통신할 서버 주소',
            changeOrigin: true,
            pathRewrite: {
                '^/api': '' // URL ^/api -> 공백 변경
            }
        })
    );
};
// rewrite path
pathRewrite: {'^/old/api' : '/new/api'}

// remove path
pathRewrite: {'^/remove/api' : ''}

// add base path
pathRewrite: {'^/' : '/basepath/'}

// custom rewriting
pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }

// custom rewriting, returning Promise
pathRewrite: async function (path, req) {
  const should_add_something = await httpRequestToDecideSomething(path);
  if (should_add_something) path += "something";
  return path;
}
profile
diet mountain dew, baby, new york city

0개의 댓글