This site runs best with JavaScript enabled.

Use a Proxy with the Angular CLI to Fix CORS Development Problems

First Published: May 12th, 2020

This week in the Angular Basics egghead collection, we're talking about proxying local servers for development. This was something that really baffled me when I was first getting started as a developer, so I'm excited to share it with you.

When we first try to use a local server for our data in development, we get a rude error in the console and nothing works. What is that and why are we getting it? Well, even though both the server and the client will eventually be on the same domain in production, we're getting CORS (cross-origin resource sharing) errors in development. That's because we're running the server and the client on different ports. We can fix this by setting up the Angular CLI to proxy all requests to the API for us so they appear to be coming from the same origin.

Check out this egghead video to learn more:

To add the proxy, first create a file in the src folder of the Angular project called proxy.conf.json. Add the following configuration:

1// src/proxy.conf.json
3 "/api": {
4 "target": "http://localhost:3001",
5 "secure": false
6 }

We then need to tell the Angular CLI to use this proxy config. In angular.json, find the serve configuration of the architects section and add a new option to the options object called proxyConfig:

1// angular.json
2"architect": {
3 // build, etc.
4 "serve": {
5 "builder": "@angular-devkit/build-angular:dev-server",
6 "options": {
7 "browserTarget": "your-application-name:build",
8 "proxyConfig": "src/proxy.conf.json"
9 },
10 // configurations, etc.
11 }

Lastly, update the HabitService so getHabits points to just /api/habits instead of the full server URL:

1// src/app/habit.service.ts
2getHabits(): Observable<Habit[]> {
3 return this.http.get<Habit[]>('/api/habits');

Now when we run npm start to start up the Express server and the client (using ng serve), the habits load onto the page. If we look at the Chrome Dev Tools network tab, we can see that the request came from localhost:4200/api/habits. No more CORS problems!

Note: this is just a fix for development. If you have CORS issues in production, the problem likely has to do with the server configuration!

You can check out the code for all of the Angular basics lessons in my egghead-angular repository on GitHub.

← Back to writing
Share article

I send emails about getting better at coding and life.

I'm on a path to become a better human and developer and I want to bring as many friends with me as possible. Want to join me? Sign up below. 👇

Sam Julien © 2020