在 HTTP 拦截器中添加 header

Add header in HTTP Interceptor

有没有办法 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);
  });
}

下面是一个 "fun" 解决方法也可以考虑。

您可以包装 jquery ajax 调用并在包装器内设置 header。我也编写了以下包装器来利用承诺。使 jQuery "feel" 更像 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 || {}));

用法(假设令牌已经被持久化)

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