gpt4 book ai didi

jquery - 在HTTP拦截器中添加 header

转载 作者:行者123 更新时间:2023-12-01 03:32:44 25 4
gpt4 key购买 nike

有没有办法使用 jQuery 来拦截所有传出的 HTTP 请求以添加授权 header ?

我知道这可以用 Angular 来完成。

所以,就像(显然我不希望它这么容易 - 但它会很酷!)

$('document').On('HttpRequest', function() {
$http.defaults.headers.common["Authorization"] = 'Bearer ' + myBearer;
});

最佳答案

ajaxSend 的回调中设置 header 对我来说很有效。

function getToken() {
return window.localStorage.getItem('token');
}

function setupAuth() {
$(document).ajaxSend(function (event, jqXhr) {
var token = getToken();
jqXhr.setRequestHeader('Authorization', 'Bearer ' + token);
});
}

下面是一个值得考虑的“有趣”解决方法。

您可以包装 jquery ajax 调用并在包装器内设置 header 。我编写了以下包装器来利用 Promise。使 jQuery“感觉”更像 angularJS(至少对于 HTTP 调用而言)。

[此处查看 GIST]( https://gist.github.com/wickdninja/66758a9d5d93c482cb5ef1803b38f72d

                var Http = (function ($, storage, self) {
var _contentType = 'application/json; charset=utf-8',
_dataType = 'json',
_key = 'token';

function getToken() {
return storage.getItem(_key);
}

function setAuthHeader(xhr) {
var token = getToken();
if (!token) return;
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
}

function get(url) {
var method = 'GET';
var deferred = $.Deferred();
ajax({
deferred: deferred,
method: method,
url: url
});
return deferred.promise();
}

function post(url, payload) {
var method = 'POST';
var deferred = $.Deferred();
var json = JSON.stringify(payload);
ajax({
deferred: deferred,
json: json,
method: method,
url: url
});
return deferred.promise();
}

function patch(url, payload) {
var method = 'PATCH';
var deferred = $.Deferred();
var json = JSON.stringify(payload);
ajax({
deferred: deferred,
json: json,
method: method,
url: url
});
return deferred.promise();
}

function put(url, payload) {
var method = 'PUT';
var deferred = $.Deferred();
var json = JSON.stringify(payload);
ajax({
deferred: deferred,
json: json,
method: method,
url: url
});
return deferred.promise();
}

function del(url) {
var method = 'DELETE';
var deferred = $.Deferred();
ajax({
deferred: deferred,
method: method,
url: url,
});
return deferred.promise();
}

function ajax(cfg) {
$.ajax({
type: cfg.method,
crossDomain: true,
url: cfg.url,
data: cfg.json,
contentType: _contentType,
dataType: _dataType,
beforeSend: setAuthHeader,
success: function (response) {
cfg.deferred.resolve(response);
},
error: function (xhr, ajaxOptions, thrownError) {
cfg.deferred.reject(thrownError);
}
});
}

self.post = post;
self.patch = patch;
self.put = put;
self.get = get;
self.delete = del;
return self;
}(jQuery, window.localStorage, Http || {}));

使用(假设 token 已经被持久化)

Http.get('url/to/api')
.then(res => {//do something with response})
.catch(err => {// do something with error});

关于jquery - 在HTTP拦截器中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45835038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com