[英]jQuery JSONP ajax, authentication header not being set
I'm trying to make an ajax request to the google contacts API with the following setup: 我正在尝试使用以下设置向google contacts API发出ajax请求:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. 但是身份验证标头似乎没有设置。 Any ideas?
有任何想法吗?
I had the same problem recently. 我最近遇到了同样的问题。 Try this:
试试这个:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. 编辑:看起来无法用JSONP完成。 Modify HTTP Headers for a JSONP request
修改JSONP请求的HTTP标头
When authentication is needed in a cross domain request, you must use a proxy server of some sort. 在跨域请求中需要身份验证时,必须使用某种代理服务器。
Since using dataType: jsonp
results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax
will not be used. 由于使用
dataType: jsonp
导致实际从添加到DOM的脚本生成HTTP请求,因此不会使用$.ajax
设置的标头。
Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url 似乎大多数OAUTH2 REST资源都接受access_token参数作为请求URL的一部分
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead: 请尝试以下代码:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});
Just do this (jquery 2.0, but should work in previous versions) 只是这样做(jquery 2.0,但应该在以前的版本中工作)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.