【问题标题】:How to send header data in http request in Angular js如何在Angular js中的http请求中发送标头数据
【发布时间】:2013-12-18 01:20:29
【问题描述】:
在尝试访问安全 Api 时,我需要在我的角度 http 请求中发送标头数据
javascript代码:
$http.post('http://localhost/api/validate', user).success(function () {
$scope.reset();
$scope.activePath = $location.path('/');
如何在此请求中发送标头数据?
【问题讨论】:
标签:
javascript
html
ajax
angularjs
【解决方案1】:
对于身份验证,我发现这段代码很有帮助。假设登录成功后token保存在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');
})
【解决方案2】:
//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()
【解决方案3】:
设置 HTTP 标头
$http 服务会自动将某些 HTTP 标头添加到所有请求中。这些默认值可以通过访问 $httpProvider.defaults.headers 配置对象来完全配置,当前包含这个默认配置:
$httpProvider.defaults.headers.common(所有请求都通用的标头):
接受:application/json、text/plain、*/*
$httpProvider.defaults.headers.post:(POST 请求的标头默认值)
内容类型:application/json
$httpProvider.defaults.headers.put(PUT 请求的标头默认值)
内容类型:application/json
要添加或覆盖这些默认值,只需在这些配置对象中添加或删除一个属性。要为除 POST 或 PUT 之外的 HTTP 方法添加标头,只需添加一个新对象,并将小写的 HTTP 方法名称作为键,例如`$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
默认值也可以在运行时通过 $http.defaults 对象以相同的方式设置。此外,您可以在调用 $http(config) 时传递的配置对象中提供 headers 属性,它会覆盖默认值而不全局更改它们。