0%

angular-proxy-config

Introduction

When you are developing an Angular application, you may need to call some APIs from the backend server. But in the development environment, the backend server may not be ready yet, or you want to use a local backend server for testing. In this case, you can use the proxy configuration to redirect the API requests to another server.

1. Create proxy file

Create a new file named proxy.conf.json in the root src folder of your Angular project. The content of the file should look like this:

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

In this example, we are redirecting all requests that start with /api to http://localhost:3000. You can change the target URL to your backend server address.

2. Update angular.json

Open the angular.json file in the root of your Angular project. Find the serve section under projects > your-project-name > architect > serve > configuration > development. Add the proxyConfig option with the path to the proxy.conf.json file.

1
2
3
4
5
6
7
8
9
10
11
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "angular-16:build:production"
},
"development": {
"proxyConfig": "src/proxy.conf.json", // <--- Add this line
"browserTarget": "angular-16:build:development"
}
},

Note: you can also serve the proxy file in ng serve command as below.

1
ng serve --proxy-config src/proxy.conf.json

3. Start the development server

Now you can start the development server with the following command:

1
ng serve

4. Example of backend server(Express)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const express = require('express');
const app = express();
const port = 3000;

// Sample user information
const userInfo = {
id: 1,
name: 'John Doe',
email: 'john.doe@example.com'
};

// Define the /api/user route
app.get('/api/user', (req, res) => {
res.json(userInfo);
});

// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

5. Troubleshooting

  1. Make sure your backend server is running on the specified target URL. you can test your api from the browser or using tools like Postman to make sure it works.
  2. Don’t call backend api directly, only calls made to dev server will be proxied.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    fetchUser() {
    return this.http.get<any>('/api/user'); // OK
    }

    fetchUser() {
    return this.http.get<any>('http://localhost:4200/api/user'); // OK
    }

    fetchUser() {
    return this.http.get<any>('http://localhost:3000/api/user'); // Won't work!
    }
  3. Make sure the path of proxy config file is correct in angular.json file.