【问题标题】:How can I rewrite the path in a reverse proxy with Angular-CLI?如何使用 Angular-CLI 重写反向代理中的路径?
【发布时间】:2021-04-29 16:50:29
【问题描述】:

我已经使用 angular2 CLI 设置了反向代理,如下所示:

{
  "/api/customer/*": {
    "target": "http://localhost:9010",
    "secure": false
  }
}

我的问题是远程 API 在路径 /customer 上公开服务,但反向代理发送的请求在 /api/customer 上。

有没有办法从反向代理发送的请求中删除 /api? (不要回答“只从你的 http 请求中删除 /api”,因为我在 /customer 上有一个角度路由)。

【问题讨论】:

    标签: angular proxy angular-cli


    【解决方案1】:

    你可以很容易地做到这一点,像这样使用pathRewrite 选项:

    proxy: {
        '/api/customer/*': {
            target: 'http://localhost:9010',
            pathRewrite: {'^/api' : ''}
        }
    }
    

    您也可以查看Updated Webpack documentation 了解更多信息。

    【讨论】:

      【解决方案2】:

      使用与 alex 的答案相同的配置来完成这项工作。但是,向前端 Web 服务器而不是后端服务器发出实际 API 请求至关重要。

      例如,我的后端在 2777 端口上运行,而我的前端在 1777 端口上运行

      module.exports = {
        '/api': {
          target: 'http://localhost:2777',
          pathRewrite: {'^/api': ''},
          logLevel: 'debug'
        }
      }
      

      而 environment.ts 中 API 请求的基本 URL 是:

      apiBaseUrl: 'http://localhost:1777/api'
      

      实际的请求如下所示:

      login(userCredentials: UserCredentials): Observable<User> {
        return this.http.post(environment.apiBaseUrl + '/auth/login', userCredentials).pipe(
          tap((user: User) => { this.authUser = user })
        )
      }
      

      这很好,因为它避免了后端服务器上对 CORS 策略的需求。希望这可以帮助某人。当我执行此设置时,我总是忘记将我的 HTTP 请求指向前端服务器,这会导致找出问题所在的无尽痛苦。

      【讨论】:

      猜你喜欢
      • 2019-08-05
      • 2019-04-04
      • 2018-07-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2015-09-13
      • 2014-03-17
      • 2014-03-24
      相关资源
      最近更新 更多