) ajaxSetup(beforeSend未起作用)

9

登录到远程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

我尝试在ajax调用中修改标题,但没有成功。

2个回答

17

更新的回答

从 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 ) );
    }
});

注意:在调用此函数之前,authorization变量应该已经设置好了


旧答案

$(function(){
    $.ajaxSetup({
        beforeSend: function(xhr) {
                 xhr.setRequestHeader('Authorization', authorization);
             }
    });
});

要使用ajaxSetup,您需要在document.ready中调用它。


1
谢谢...这个方法有效...我也发现了如何使beforeSend在ajax调用块中工作... 我忘记添加: async:false ..$.ajax('https://macMini.local:8000/Categories', { type: "GET", cache: false, async: false, dataType: "json", beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization', 'Bearer ' + amplify.store("tokens").access_token); } }) - user762579
这可能已经过时了,现在您可以直接在$.ajax()中设置“headers”属性。 - MonoThreaded
@MonoThreaded 更新了答案,感谢你指出这一点。没有你,我不会注意到这个问题。 - abc123

0

我知道这是一个老问题,但我是从谷歌来的,想着其他搜索同样问题的人应该有一个可行的解决方案。我尝试了建议的答案,但对我来说它不起作用。

一个解决我的问题的方法是直接在xhr对象中设置头部,在$.ajaxSend中:

$(document).ajaxSend(function(ev, xhr, settings) {
  xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem(AUTH_TOKEN)}`);
  xhr.setRequestHeader('X-Marketplace', localStorage.getItem('marketplace'));
});

你应该在 document.ready 中调用它,以使 ajaxSend 起作用。

那个类似的 问题 帮了我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接