简体   繁体   English

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

[英]How can I rewrite the path in a reverse proxy with Angular-CLI?

I have set up the reverse proxy with the angular2 CLI like the following:我已经使用 angular2 CLI 设置了反向代理,如下所示:

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

My problem is that the remote API is exposing a service on the path /customer, but the request that is sent by the reverse proxy is on /api/customer.我的问题是远程 API 在路径 /customer 上公开服务,但反向代理发送的请求在 /api/customer 上。

Is there a way to remove the /api from the request that is sent by the reverse proxy?有没有办法从反向代理发送的请求中删除 /api ? (Don't answer with "just remove the /api from your http request", because I have an angular route on /customer). (不要回答“只是从您的 http 请求中删除 /api”,因为我在 /customer 上有一个角度路由)。

You can do this fairly easy, using the pathRewrite option like so:你可以很容易地做到这一点,使用pathRewrite选项,如下所示:

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

You can also take a look at theUpdated Webpack documentation for further information.您还可以查看更新的 Webpack 文档以获取更多信息。

Got this working using the same config as alex's answer.使用与亚历克斯的答案相同的配置来完成这项工作。 However, its essential to make your actual API requests to the frontend web server and not to the backend server.但是,将实际 API 请求发送到前端 Web 服务器而不是后端服务器至关重要。

For example, my backend is running on port 2777 and my frontend is running on port 1777例如,我的后端在端口 2777 上运行,而我的前端在端口 1777 上运行

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

And the base URL for API requests in environment.ts is: environment.ts 中 API 请求的基本 URL 是:

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

And an actual request would look like:一个实际的请求看起来像:

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

This is great because it avoids the needs for CORS policies on the backend server.这很好,因为它避免了后端服务器上对 CORS 策略的需求。 Hope this helps someone.希望这可以帮助某人。 I always forget to point my HTTP requests to the frontend server when I do this setup which causes endless pain figuring out what's wrong.当我做这个设置时,我总是忘记将我的 HTTP 请求指向前端服务器,这会导致无尽的痛苦找出问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM