Introduction
While working in Angular, we fetch data from API. Every time we make the call, we write full API URL. But there can be a case when our API URL changes or we want to avoid rewriting the full URL. So this Angular provides 'proxy configuration'.
Background
Basic understanding to set up an Angular project is required. Just follow the steps and we will be able to achieve our target.
Using the Code
- First thing first, create a 'proxy.config.json' file (where package.json exits).
- Write the following code in it:
{
"/api/*": {
"target": "http://jsonplaceholder.typicode.com",
"secure": false,
"pathRewrite": {"^/api" : ""},
"changeOrigin":true,
"logLevel": "debug"
}
}
Note: Do add pathRewrite
line in this file... this is responsible for calling any API call if you call it like
/api/users or /api/posts.
{
"name": "ng6",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
-------
- Update the package.json so that proxy server is enabled when you start your project.
The above line tells the npm
to create the proxy for API.
Note: Please stopping current running server first and then use 'nmp start
' command as this will result in calling 'ng serve --proxy-config proxy.config.jso
'.
- Calling the API: Call the API using
get
/post
method like below:
getUsers(){
return this.http.get('/api/users')
}