Squirrl
Squirrl

Reputation: 4966

How do you pass in HTTP headers to make a request from an API?

Using Angular, I'm trying to pass in HTTP headers with the request, “App-Id” and “App-Key” to get data from this API.

I tried setting the headers like this:

 $http.defaults.headers.common["App-Id"] = '5a3d8b8d';
 $http.defaults.headers.common["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';

but I got a Response for preflight is invalid error.

http://jsfiddle.net/9Ymvt/4573/

Upvotes: 0

Views: 3754

Answers (3)

georgeawg
georgeawg

Reputation: 48968

Adding Headers to an $http Request on a Per Request Basis

To add headers to a $http request on a per request basis, add them to the headers property of the $http config object.

var xheaders = {};
xheaders["App-Id"] = '5a3d8b8d';
xheaders["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';

var xurl = 'https://uk.bookingbug.com/api/v1';
var configObj = { method: 'GET',
                  url: xurl, 
                  headers: xheaders
                };
$http(configObj)
    .then(function onFulfilled(response) {
        console.log(response);
        vm.headers = response.config.headers;
        vm.data = response.data
    }).catch( function onRejection(errorResponse) {
        console.log("Error: ", errorResponse.status);
        console.log(errorResponse);
        vm.error = errorResponse;
    })
;

The code was getting pre-flight errors because it was using the incorrect URL. The correct base URL is https://uk.bookingbug.com/api/v1 which supports App-Id headers and CORS.

The DEMO on JSFiddle.

Upvotes: 1

errata
errata

Reputation: 26862

Preflight errors are related to CORS. You might want to look at rack-cors to enable cross-site api calls via javascript. There is a manual configuration here: https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4

Upvotes: 1

Jeff Diederiks
Jeff Diederiks

Reputation: 1380

I do not think this is a complete answer to your question, but here is what I have in my project:

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
  // code for routes
});
app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

This solves my problem with CORS. If you want to do another type of header, you probably can find your answer here.

Upvotes: 1

Related Questions