Click here to Skip to main content
15,887,175 members
Articles / AngularJs / Angular6
Tip/Trick

Angular Proxy Configuration for API Calls

Rate me:
Please Sign up or sign in to vote.
4.87/5 (4 votes)
5 Sep 2018CPOL 14.8K   4  
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)


Written By
Software Developer
India India
Puneet Goel is an IT Professional with 8+ years. He is specialized in Microsoft Technologies (Asp.NET, SQL Server, Ajax, Jquery, JavaScript, MVC, and Angular). He is an avid member of several development communities and a serial blogger.He loves to learn new technology, do experiments with existing ones, and always happy to help the community.

Comments and Discussions

 
-- There are no messages in this forum --