How To Proxy API requests In Angular Application

In this blog post, I will discuss HttpInterceptor in more detail.

What is # HttpInterceptor in Angular

HttpInterceptor is a component in Angular that intercepts requests and responses in the angular application.

Where to use the Angular HttpInterceptor

The HttpInterceptor has various uses in angular. Here are a few examples that we used in almost every angular project.

  • Centralized error handling
  • Modifying the HTTP headers
  • Adding token to HttpResponse
  • Creating proxy
  • Logging the request and response
    and many more.

How to create and use HttpInterceptor in angular applications

You can create a custom HTTP interceptor in the angular application by creating a class and then implementing the HttpInterceptor interface which has one method intercept

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

After creating the interceptor you need to register in the main module of the angular application

import { TokenInterceptor } from './../auth/token.interceptor';@NgModule({  
  bootstrap: [AppComponent],  
  imports: [...],  
  providers: [  
    {  
      provide: HTTP_INTERCEPTORS,  
      useClass: TokenInterceptor,  
      multi: true  
    }  
  ]  
})  
export class AppModule {} 

In this example, I will create a simple proxy interceptor that forwards the request to the real server based on the proxy address.

client request http interceptor
client.get(‘proxy/posts’ client.get(‘https://jsonplaceholder.typicode.com/posts

The idea here is that we intercepts the request in http interceptor and then check that if URL start with proxy then we replace the URL with real one. You can extend this logic easily for example based on the environment you can change the URL

What is proxy request?

Before div into coding lets understand what is proxy request.

When you send a web request, it first goes to the proxy server. The proxy server then makes your web request on your behalf, receives the response from the web server, and forwards the web page data to you so you can view it in your browser.

For this example I am using stackbliz web IDE. I have created a new application and then I have created a interceptor named ProxyInterceptor as you can see below

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class ProxyInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(
    httpRequest: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (httpRequest.url.startsWith('/proxy')) {
      const newRequest = httpRequest.clone({
        url: httpRequest.url.replace(
          '/proxy',
          'https://jsonplaceholder.typicode.com'
        ),
      });

      return next.handle(newRequest);
    } else {
      return next.handle(httpRequest);
    }
  }
}

In the above code, I intercept the request and then check if the request URL begins with ‘proxy,’ if so, I replace the URL with the real one.

The next step is to include the Http Interceptor in the ‘app.module’ file.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ProxyInterceptor } from './proxy-interceptor';

@NgModule({
  imports: [BrowserModule, FormsModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ProxyInterceptor, multi: true },
  ],
})
export class AppModule {}

Then In the app.component.ts in the constructor I am making http request call as shown below

import { HttpClient } from '@angular/common/http';
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  data: any;
  constructor(private http: HttpClient) {
    this.http.get('/proxy/posts').subscribe((data) => (this.data = data));
  }
}

app.component.htm

{{ data | json }}

If you run the application you will see that list of posts as a JSON in the UI

happy coding 😊

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post