Making Proxy Request In Angular/Fix CORS Issue In Angular Applications

This Article shows how to make proxy calls or fix the CORS issue in an Angular Application. When we want to communicate out of our Angular application we try to call the WebApi.Here we might face a common issue known as CORS issue.

When we want to communicate out of our Angular application, we try to call a WebAPI. Here, we might face a common issue known as a CORS issue.

CORS – Cross-Origin Resource Sharing

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

If you are not that familiar with CORS read about CORS first then continue with this article.

Angular runs on its own server (by default localhost:4200) and webAPI runs on a different port so we get the Cors issue.

Making Proxy request in Angular / Fix CORS issue in Angular Application

So, from the above screen, it is clear that WebAPI is running on port 57263 and our application is running on 4599 (it's not running in 4200 as I have changed the port in package.json).

http://localhost:4599 - http://localhost:57263 (here domain is same but the port number is different - one of the rules to satisfy CORS)

So, the solution for the above issue is,

  • Angular proxy (client-side solution)
  • Enable CORS on the webAPI (Server Side)

In this article, we will see a detailed explanation on how to use Angular Proxy only. This example is created using Angular CLI version 6.

Step 0

Create a .NETWebAPI with the below sample methods. 
 
Making Proxy request in Angular / Fix CORS issue in Angular Application
 
Step 1
 
Create an AngularCLI Project named “AngularProxyApp”

Step 2

Create the Service File and all the Code for Service Call.

Step 3

Call the Service from the app.component.ts

Here, only the structure and code snippets are shown, you can put it together for a proxy shows.

Project structure

Making Proxy request in Angular / Fix CORS issue in Angular Application
 
test.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';  
  3. import { Observable } from 'rxjs';  
  4. @Injectable()  
  5. export class TestService {  
  6.    constructor(private http: HttpClient) { }  
  7.       getBaseUrl() {  
  8.       return 'http://localhost:57263/';  
  9.    }  
  10. getTestMessage(): Observable<string> {  
  11.    const headers = new HttpHeaders({ 'Content-Type''text/plain'});  
  12.    return this.http.get(this.getBaseUrl() + 'api/Home/FetchValues', {responseType: 'text', headers});  
  13.  }  
  14. }  

 

Calling the service method “getTestMessage” from app.component.ts. 
 
app.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { TestService } from './services/test.service';  
  3. import { Observable } from 'rxjs';  
  4. @Component({  
  5.    selector: 'app-root',  
  6.    templateUrl: './app.component.html',  
  7.    styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent implements OnInit {  
  10.    title = 'app';  
  11.    testMessage$: Observable<string>;  
  12.    constructor(private testService: TestService) { }  
  13. ngOnInit() {  
  14.    this.getTestMessage();  
  15. }  
  16. getTestMessage () {  
  17.     this.testService.getTestMessage().subscribe(data => console.log(data));  
  18. }  
  19. }  

 

Don’t forget about App.module, we need to do some changes here as well.
 
App.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { TestService } from './services/test.service';  
  5. import { AppComponent } from './app.component';  
  6. @NgModule({  
  7.    declarations: [  
  8.    AppComponent  
  9. ],  
  10. imports: [  
  11.    BrowserModule,  
  12.    HttpClientModule  
  13. ],  
  14. providers: [TestService],  
  15.    bootstrap: [AppComponent]  
  16. })  
  17. export class AppModule { }  

Now, with the above setup if you run the app using npm start it will give CORS issue as explained above,

 
Making Proxy request in Angular / Fix CORS issue in Angular Application 
Here, anybody can know where our API is hosted. So, if we want to hide the WebAPI hosted address and fix the CORS issue we can go for the proxy request.

Step 4

Create proxy.conf.json,
 
Making Proxy request in Angular / Fix CORS issue in Angular Application
 
Proxy.conf.json
  1. {  
  2.    "/api/*": {  
  3.       "target""http://localhost:57263",  
  4.       "secure"false,  
  5.       "logLevel""debug"  
  6.    }  
  7. }  
Step 5
 
Add ProxyConfig key in Angular.json file.
 
Angular.json
  1. "serve": {  
  2.    "builder""@angular-devkit/build-angular:dev-server",  
  3.    "options": {  
  4.       "browserTarget""AngularProxyApp:build",  
  5.       "proxyConfig""proxy.conf.json"  
  6. },
Step 6
 
Change in Package.json File,
 
package.json
  1. "scripts": {  
  2.    "ng""ng",  
  3.    "start""ng serve --port 4599 --proxy-config proxy.conf.json",  
  4.    "build""ng build",  
  5.    "test""ng test",  
  6.    "lint""ng lint",  
  7.    "e2e""ng e2e"  
  8. }, 
Now, change the test.service.ts as well to- 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';  
  3. import { Observable } from 'rxjs';  
  4. @Injectable()  
  5. export class TestService {  
  6.    constructor(private http: HttpClient) { }  
  7.    getBaseUrl() {  
  8.       return 'http://localhost:57263/';  
  9.    }  
  10.    getTestMessage(): Observable<string> {  
  11.       const headers = new HttpHeaders({ 'Content-Type''text/plain'});  
  12.       return this.http.get('api/Home/FetchValues', {responseType: 'text', headers});  
  13.    }  
  14. }  
Remove the URL as now it will use proxy.conf.json file when we run npm start.

Now, all the setup is done for making a proxy request. Now, when we run the Application using npm start:

  1. It runs ng serve --port 4599 --proxy-config proxy.conf.json command
  2. Our Angular App runs on port 4599 and calls the proxy.conf.json so any API request having api/* takes the target from proxy.conf.json

    Below when we run npm start we can see that a proxy is created.

    Making Proxy request in Angular / Fix CORS issue in Angular Application

  3. There is no CORS issue and if we check the network the original Web request is hidden with the URL of the Angular server.

    Making Proxy request in Angular / Fix CORS issue in Angular Application 
The requested URL should be http://localhost:57263/api/Home/GetValues but it is http://localhost:4599/api/Home/GetValues
 
Advantages
  1. Fixes the CORS issue
  2. Proxy.conf.json can be used to redirect the request to different servers.
  3. Hide the wepi URLs from the Network 
Hope you all enjoyed reading this article.