登录到远程aPI服务器并获取access_token后,我尝试为所有后续的ajax调用设置授权头:
.done(function (result) { console.log("GOT AUTHORIZATION"); amplify.store( "tokens",{ access_token: result.access_token,refresh_token: result.refresh_token,token_type: result.token_type,expires_in: result.expires_in }); var authorization = 'Bearer ' + amplify.store( "tokens" ).access_token; console.log(authorization); $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Authorization',authorization); } });
在控制台上,我可以看到:
GOT AUTHORIZATION login.js:34 Bearer 6b7578772fbb4178793100651f2234de840237fe
但后续的ajax调用都没有得到正确的标头集:
https://macmini.local:8000/Categories?_=1381758170726
无法成功,因为在标头(服务器控制台..)中找不到access_token
{ code: 400,error: 'invalid_request',error_description: 'The access token was not found',stack: undefined } saveAccessToken: 6b7578772fbb4178793100651f2234de840237fe,client_id: 1234567890,user_id: 1
解决方法
更新的答案
从jQuery 1.5开始,.ajax支持headers属性
$.ajax({ url: "http://fiddle.jshell.net/favicon.png",headers: { 'Authorization': authorization } }) .done(function( data ) { if ( console && console.log ) { console.log( "Sample of data:",data.slice( 0,100 ) ); } });
注意:应在此调用之前的某处设置授权变量
老答案
$(function(){ $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Authorization',authorization); } }); });
要使ajaxSetup工作,您需要在document.ready中调用它.