공부일지(TIL)/Web

[http-proxy-middleware] path rewrite, target

Alledy 2023. 3. 27. 21:33
const proxy = require('http-proxy-middleware'); 

module.exports = function(app) { 
    app.use( proxy('/posts', { 
        target:'https://target.domain.com', 
        changeOrigin: true 
        }) 
    ); 
};

흔히 cors 문제를 해결하기 위해 프록시를 사용할 수 있는데, http-proxy-middleware를 사용해서 위처럼 설정하면 /posts로 시작하는 API는 target 필드에 설정한 서버로 호출하게 된다. 즉 /posts/1 을 호출하면, https://target.domain.com/posts/1 을 호출하게 된다.

const proxy = require('http-proxy-middleware'); 

module.exports = function(app) { 
    app.use( proxy('/old-posts', { 
          pathRewrite: {
            '^/old-posts': '/new-posts'
        },
        target:'https://target.domain.com', 
        changeOrigin: true 
        }) 
    ); 
};

pathRewrite 객체는 key에 매핑된 api path를 value로 치환해준다. 위의 경우에는 /old-posts를 호출하면 https://target.domain.com/new-posts 를 호출하게 된다.

Ref

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