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

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.

For example, my backend is running on port 2777 and my frontend is running on port 1777

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

And the base URL for API requests in environment.ts is:

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. 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.


You can do this fairly easy, using the pathRewrite option like so:

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

You can also take a look at the Updated Webpack documentation for further information.