如何在Angular JS中访问$http服务请求object?

How to access the $http service request object in Angular JS?

我正在使用 $http 服务发出 http 请求,如下所示:

$http({
        url: "URL",
        method: "POST",
        data: payload,
        headers :{
            "Content-Type": "application/json",
            "access_token": xyz
        }                
    }).then(function (response) {
        $log.debug("Response :",response);
    }, function (error) {
        $log.debug("error :",error);
    });

我需要访问我发送的请求 object(以及 headers 等)。代码中可以吗?

使用 interceptor. Here is a good article 和其中的示例。

module.factory('timestampMarker', [function() {  
    var timestampMarker = {
        request: function(config) {
            config.requestTimestamp = new Date().getTime();
            return config;
        },
        response: function(response) {
            response.config.responseTimestamp = new Date().getTime();
            return response;
        }
    };
    return timestampMarker;
}]);

module.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('timestampMarker');
}]);

使用拦截器将使您能够读入或向请求添加 headers 等。希望对您有所帮助。

您可以看到示例中的请求属性:

$http.post('/service', params).success(
    function(data, status, headers, config) {
        //...
        console.log('properties', config.method, config.headers['Content-Type'], config);
});

或者,如果您想 see/change 属性 before/after 以更全局的方式请求,您可以使用拦截器:

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(['$q', function($q) {
        return {
            'request': function(config) {
                // for example:
                config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                // same more logic ...

                return config;
            },
            'response': function(response) {
                // for example:
                if (!response.data || !response.data.status) {
                    return $q.reject(response);
                }
                // same more logic ...

                return response;
            },
            'responseError': function(rejection) {
                // same more logic ...
            }
        };
    }]);
}]);