How To get Rid of Access Control Allow Headers in Angular

Posted By : Rajat khurana | 30-Nov-2017

Hi guys, here you will learn how to get rid of "Access-Control-Allow-Headers". First of all, you need to  know when this error occurs. It occurs when you are using third party API directly in Angular with $http service or using observable. Instead of using third party API directly you will hit this API with backend server. Now mostly backend system is made in Java and node js.

If you have backend in Java then some thing related to cors. Here is something related to code..

@Override public void addCorsMappings(CorsRegistry registry) 
{ 

 registry.addMapping("/**").allowedOrigins("*").allowedMethods("*"); 

}`enter code here`

 

Now when your backend in Node js ,you just hit third party  API. There are different modules developed in node js for sending data to a url i.e related to hitting any API. DIfferent modules are http, request , axios , got and superagent etc. Lot of options or modules available in node js. We will discuss one by one all. 

1 Http is standard library for sending a request to any url. Its code length is large as compared to others.

var https = require('https');

https.get('Any Url of API to be hit', (resp) => {
  let data = '';

  //  data that has been recieved
  resp.on('data', (chunk) => {
    data += chunk;
  });

  //  whole response will be  received.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Error occur: ",err);
});

Above is code to hit API using HTTP module. Now another module is request.

2. Request module is simplified and comparabe to request libraray in Python. It is usr friendly and most developers use it on a age scal because only few lined of code is needed in this module.

var request = require('request');    
request('Url of API which you want to hit', { json: true }, (err, res, body) => {
      if (err) { console.log("Error will occur",err); }
      else
      console.log("Response is in body",body);
    });

This is how we can use request module.

About Author

Author Image
Rajat khurana

Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.

Request for Proposal

Name is required

Comment is required

Sending message..