[英]Unable to properly set custom headers using angular
I have an .net WebAPI project running on IIS with CORS enabled. 我在启用了CORS的IIS上运行一个.net WebAPI项目。 This project has an authorization handler which check for a header named "Token" in every request, for now it only checks if it has a string value. 该项目具有一个授权处理程序,该处理程序在每个请求中都检查一个名为“ Token”的标头,现在它仅检查它是否具有字符串值。
In my API call with angular, I'm using the following line to add headers. 在我用angular进行的API调用中,我使用以下行添加标头。 I took this from the angular documentation 我从角度文件中拿走了
$http.defaults.headers.common['Token'] = 'C3POR2D2'; $ http.defaults.headers.common ['Token'] ='C3POR2D2';
Raw data from fiddler for the API is as follows. 来自fiddler的API原始数据如下。
OPTIONS http://localhost:81/api/Sample/GetSubordinateRolesForUser/1 HTTP/1.1
Host: localhost:81
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.45 Safari/537.36
Access-Control-Request-Headers: accept, token
Accept: */*
Referer: http://localhost/Account/Login
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
In here 'token' appears as a value under Access-Control-Request-Headers. 在这里,“令牌”作为值出现在Access-Control-Request-Headers下。 This is causing my authorization handler to return a 403 Forbidden, as it is expecting the header 'Token' with some string value. 这导致我的授权处理程序返回403 Forbidden,因为它期望标头'Token'具有一些字符串值。
Following is the response raw data 以下是响应原始数据
HTTP/1.1 403 Forbidden
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Headers: Token
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Date: Wed, 07 Jan 2015 11:28:43 GMT
Content-Length: 0
What am I missing here? 我在这里想念什么?
use this. 用这个。 i also face the similar issues 我也面临类似的问题
function getSettings(requestData) {
return {
url: requestData.url,
dataType: requestData.dataType || "json",
data: requestData.data || {},
headers: requestData.headers || {
"accept": "application/json; charset=utf-8",
'Authorization': requestData.token
},
async: requestData.async || "false",
cache: requestData.cache || "false",
success: requestData.success || {},
error: requestData.error || {},
complete: requestData.complete || {},
fail: requestData.fail || {}
};
}
and call this like this way 并这样称呼它
var requestData = {
url: 'your API end point',
data: project,
token: yourtoken
};
var settings = getSettings(requestData);
settings.method = "POST"; //Your request
return $http(settings);
and remove $http.defaults.headers.common['Token'] = 'C3POR2D2'; 并删除$ http.defaults.headers.common ['Token'] ='C3POR2D2';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.