【问题标题】:Angular2/Angular seed http-proxy-middleware proxy api requestsAngular2/Angular 种子 http-proxy-middleware 代理 api 请求
【发布时间】:2017-08-21 10:14:44
【问题描述】:

我正在使用Angular Seed project 并尝试为在不同端口上运行的后端服务的 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'
    }
  })
];

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

【问题讨论】:

    标签: api angular proxy http-proxy-middleware


    【解决方案1】:

    花了一些时间尝试完成这项工作,这就是我最终在构造函数中添加到 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');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2023-03-26
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多