Use proxy in Angular CLI

It’s common for an Angular 4 project to use proxy during development to workaround the same-origin policy, especially when the server-side is not developed using Node.js. If the Angular 4 project is created using Angular CLI, we can add a proxy.conf.json file in the root directory to configure the proxy.

1
2
3
4
5
6
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}

Then edit the start script in package.json.

1
"start": "ng serve --proxy-config proxy.conf.json",

Angular CLI uses the webpack-dev-server as the development server. webpack-dev-server uses http-proxy-middleware as the proxy, which provides more options to configure.

Update for Angular 6

If you are using Angular 6, you can put the proxy config into the angular.json file for Angular CLI. You need to locate the configuration for serve task and add the proxyConfig option. In the following file, the proxy config file src/proxy.conf.json is configured.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "example:build",
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "example:build:production"
}
}
}
}

Basic authentication

Add basic authentication header for requests to target server.

1
2
3
4
5
6
{
"/api": {
"target": "http://localhost:3000",
"auth": "user:password"
}
}

Custom headers

Add custom headers for requests to target server.

1
2
3
4
5
6
7
8
{
"/api": {
"target": "http://localhost:3000",
"headers": {
"X-UID": "id"
}
}
}

Rewrite path

Rewrite path.

1
2
3
4
5
6
7
8
{
"/api": {
"target": "http://localhost:3000",
"pathRewrite": {
"^/old/api" : "/new/api"
}
}
}
Comments