Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / AngularJs / Angular6

Angular Proxy Configuration for API Calls

4.87/5 (4 votes)
5 Sep 2018CPOL 15.3K  
This is about how we can set up proxy to make API call in Angular applications.

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

  1. First thing first, create a 'proxy.config.json' file (where package.json exits).
  2. Write the following code in it:
    JavaScript
    {
       "/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.

    JavaScript
    {
      "name": "ng6",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxy.config.json",
        -------
  3. 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'.

  4. Calling the API: Call the API using get/post method like below:
    JavaScript
    getUsers(){
      return this.http.get('/api/users')
    }
    

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)