Angular2/Angular 种子 http-proxy-middleware 代理 api 请求

2024-04-11

我正在使用角种子项目 https://github.com/mgechev/angular-seed/tree/master/tools并尝试为在不同端口上运行的后端服务的 api 请求设置代理。

到目前为止我的代码:

/* Add proxy middleware */
this.PROXY_MIDDLEWARE = [
  require('http-proxy-middleware')({
    ws: false,
    target: 'http://localhost:5555',
    router: {
      // when request.headers.host == 'dev.localhost:3000',
      // override target 'http://www.example.org' to 'http://localhost:8000'
      //'http://localhost:5555/basepath/api' : 'http://localhost:7000/api'
    }
  })
];

基本上我需要做的是路由任何 api 匹配http://localhost:5555/basepath/api http://localhost:5555/basepath/api to http://localhost:7000/api http://localhost:7000/api虽然我似乎无法使用 http-proxy-middleware 来完成这项工作。我最初使用代理中间件工作,但由于我需要修改请求标头而进行了切换,而且似乎只能使用 http-proxy-middleware 来完成。


花了一些时间尝试完成这项工作,这就是我最终添加到构造函数中的 project.config.ts 中的内容。

   /* Add proxy middleware */
    this.PROXY_MIDDLEWARE = [
      require('http-proxy-middleware')(
        '/basepath/api', {
        ws: false,
        onProxyReq: this.onProxyReq,
        target: 'http://localhost:7000',
        pathRewrite: {
          '^/basepath/api' : '/api'
        }
      })
    ];

这是我在构造函数下面包含的函数,用于向代理的任何请求添加标头

onProxyReq(proxyReq: any , req: any, res: any) {
  // add custom headers to request
  proxyReq.setHeader('header_name', 'value');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2/Angular 种子 http-proxy-middleware 代理 api 请求 的相关文章

随机推荐