简体   繁体   中英

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/

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 .

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM