붉은거위 노트 (redgoose note)

nuxt3 환경에서 proxy server 구현하기

Nest
Development
Category
Server
Hit
432
Star
0

프록시 구현에 대하여 포기할까 하는 때에 우연히 해결을 할 수 있는 코멘트를 찾았다.
서버 미들웨어 영역에서 node-http-proxy 모듈을 사용하는 방식이다.

/server/middleware/proxy.js 파일을 만들고 다음과 같이 구성을 준비한다.

import httpProxy from 'http-proxy';

const { API_URL } = useRuntimeConfig();
const proxy = httpProxy.createProxyServer({
  changeOrigin: true,
});
let prefix;

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  const exp = new RegExp(`^${prefix}`);
  let path = proxyReq.path.replace(exp, '/');
  path = path.replace(/\/\//, '/');
  proxyReq.path = path;
});

export default function (req, res, next) {
  if (req.url.startsWith('/proxy')) {
    prefix = '/proxy';
    proxy.web(req, res, {
      target: API_URL,
    });
  } else {
    next();
  }
}

path 주소 변환은 옵션에서 제공되어 있지 않아서 request 이벤트에서 처리했다.

출처: https://github.com/nuxt/framework/discussions/1223#discussioncomment-1960448