繁体   English   中英

如何在Angular js中的http请求中发送头数据

[英]How to send header data in http request in Angular js

在尝试访问安全的Api时,我需要在我的角度http请求中发送标头数据

javascript代码:

$http.post('http://localhost/api/validate', user).success(function () {
        $scope.reset();
        $scope.activePath = $location.path('/');

如何在此请求中发送标头数据?

   //store the header data in a variable 
    var headers = { 'Authorization': authToken };

    //Add headers with in your request
    $http.post('http://localhost/api/validate',user, { headers: headers } ).success(function() 

设置HTTP标头

$ http服务将自动为所有请求添加某些HTTP标头。 可以通过访问$ httpProvider.defaults.headers配置对象来完全配置这些​​默认值,该配置对象当前包含此默认配置:

$ httpProvider.defaults.headers.common(所有请求通用的标头):接受:application / json,text / plain,* / *

$ httpProvider.defaults.headers.post :( POST请求的标头默认值)Content-Type:application / json

$ httpProvider.defaults.headers.put(PUT请求的标头默认值)Content-Type:application / json

要添加或覆盖这些默认值,只需在这些配置对象中添加或删除属性即可。 要为POST或PUT以外的HTTP方法添加标头,只需添加一个带有小写HTTP方法名称的新对象作为键,例如`$ httpProvider.defaults.headers.get = {'My-Header':'value'} 。

也可以通过$ http.defaults对象以相同的方式在运行时设置默认值。 此外,您可以在调用$ http(config)时传递的config对象中提供headers属性,该属性会覆盖默认值而不会全局更改它们。

对于身份验证,我发现这段代码很有用。 假设成功登录后令牌存储在cookie中,

.factory('authInterceptor', function ($q, $cookieStore) {
    return {
        // Add authorization token to headers
        request: function (config) {
            config.headers = config.headers || {};
            if ($cookieStore.get('token')) {
                config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
            }
            return config;
        },

        // Intercept 401s and redirect you to login
        responseError: function(response) {
            if(response.status === 401) {
                // remove any stale tokens
                $cookieStore.remove('token');
                return $q.reject(response);
            }
            else {
                return $q.reject(response);
            }
        }
    };
})
.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM