Use proxy in Angular CLI

It’s common for an Angular 4 project to use proxy during development to workround the same-orign 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.

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