[英]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 . 我试图使用Angular传递HTTP标头和请求“ App-Id”和“ App-Key”,以从此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. 但是我收到一个
Response for preflight is invalid
错误。
http://jsfiddle.net/9Ymvt/4573/ 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. 这解决了我的CORS问题。 If you want to do another type of header, you probably can find your answer here .
如果您要执行其他类型的标题,则可以在此处找到答案 。
Preflight errors are related to CORS. 飞行前错误与CORS有关。 You might want to look at rack-cors to enable cross-site api calls via javascript.
您可能需要查看rack-cors以通过javascript启用跨站点api调用。 There is a manual configuration here: https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4
这里有一个手动配置: https : //gist.github.com/dhoelzgen/cd7126b8652229d32eb4
$http
Request on a Per Request Basis $http
请求 To add headers to a $http
request on a per request basis, add them to the headers
property of the $http
config object. 要在每个请求的基础上将标头添加到
$http
请求,请将其添加到$http
config对象的headers
属性。
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. 该代码收到飞行前错误,因为它使用了错误的URL。 The correct base URL is
https://uk.bookingbug.com/api/v1
which supports App-Id
headers and CORS. 正确的基本URL是
https://uk.bookingbug.com/api/v1
,它支持App-Id
标头和CORS。
The DEMO on JSFiddle . JSFiddle上的DEMO 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.