如何使用Angular CLI重写反向代理中的路径?

如何使用Angular CLI重写反向代理中的路径?,angular,proxy,angular-cli,Angular,Proxy,Angular Cli,我使用angular2 CLI设置了反向代理,如下所示: { "/api/customer/*": { "target": "http://localhost:9010", "secure": false } } 我的问题是远程API在路径/customer上公开服务,但反向代理发送的请求在/API/customer上 有没有办法从反向代理发送的请求中删除/api?(不要回答“从http请求

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

{
  "/api/customer/*": {
    "target": "http://localhost:9010",
    "secure": false
  }
}
我的问题是远程API在路径/customer上公开服务,但反向代理发送的请求在/API/customer上


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

使用
pathRewrite
选项可以相当轻松地完成此操作,如下所示:

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

您还可以查看以了解更多信息。

使用与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 })
  )
}
登录(userCredentials:userCredentials):可观察{
返回此.http.post(environment.apiBaseUrl+'/auth/login',userCredentials).pipe(
点击((用户:用户)=>{this.authUser=user})
)
}

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

您能帮我解答我的问题吗: