在HTTP Interceptor中添加标头

时间:2017-08-23 08:55:15

标签: jquery http-headers bearer-token

有没有办法让jQuery拦截所有传出的HTTP请求以添加授权标头?

我知道这可以用Angular完成。

所以,有点像(显然我不希望它变得如此简单 - 但它会很酷!)

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

1 个答案:

答案 0 :(得分:1)

ajaxSend的回调中设置标题对我有用。

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

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

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

您可以包装jquery ajax调用并在包装器中设置标头。我写了下面的包装器来使用promises。使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 || {}));

用法(假设令牌已被保留)

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