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 | { |
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 | "serve": { |
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 | const express = require('express'); |
5. Troubleshooting
- 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.
- 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
11fetchUser() {
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!
} - Make sure the path of proxy config file is correct in
angular.json
file.