向标题添加授权

时间:2018-09-04 08:13:24

标签: angular6 angular-http-interceptors xtrareport

我正在使用Angular 6和DevExpress Xtra-report模块。我想在header中添加Authorization.Well我正在使用HttpInterceptor添加Authorization及其与除xtra-report模块之外的所有其他模块的正常工作,因此我尝试在模块内部使用jquery传递授权(如下所示)无法正常工作,我对此不太满意。 我在userId中获得了令牌。

const userId = localStorage.getItem('access_token');
$.ajaxSetup({
    cache: true,
    type: 'POST',
    xhrFields: {
        withCredentials: true,
        Authorization: `Bearer ${userId}`,
    },
    complete: function (result) {
        // console.log('complete');
    },
    error: function (jqXHR, status, erreur) {
        // console.log('error');
    },
    beforeSend: function (xhr, settings) {
        console.log(`beforeSend beforeSend beforeSend beforeSend beforeSend beforeSend + ${userId}`);
        xhr.withCredentials = true;
        xhr.Authorization = `Bearer ${userId}`;
    }
});

我不知道为什么HttpInterceptor可以与我的除xtra-report模块之外的所有模块一起使用,可能是因为我懒惰地收费,或者我不知道,如果能从我这儿获得更多信息,请帮忙。 谢谢

1 个答案:

答案 0 :(得分:0)

我通过在其中添加带有Authorization的标头解决了这个问题,所以它变成了这样:

const userId = localStorage.getItem('access_token');
$.ajaxSetup({
    cache: true,
    type: 'POST',
    xhrFields: {
        withCredentials: true,
     },
     headers: {
        Authorization: `Bearer ${userId}`,
     },
    complete: function (result) {
        // console.log('complete');
    },
    error: function (jqXHR, status, erreur) {
        // console.log('error');
    },
    beforeSend: function (xhr, settings) {
        console.log(`beforeSend beforeSend beforeSend beforeSend beforeSend beforeSend + ${userId}`);
      xhr.withCredentials = true;
      xhr.Authorization = `Bearer ${userId}`;
    }
});

希望这有一天能对某人有所帮助