0
繼獲得響應報頭中的角JS是網頁API2方法返回的響應:無法從網絡API2
Response Headers
{
"cache-control": "no-cache",
"pragma": "no-cache",
"content-type": "application/json; charset=utf-8",
"expires": "-1",
"server": "Microsoft-IIS/10.0",
"token": "ac3903cc-7c9b-469a-85ea-677ff9773d43",
"tokenexpiry": "900",
"access-control-expose-headers": "Token,TokenExpiry",
"x-aspnet-version": "4.0.30319",
"x-sourcefiles": "=?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcV2ViQXBpXFJlc3RXZWJBUElcV2ViQXBpRG9zQWRtaW5cV2ViQXBpRG9zQWRtaW5cYXBpXGF1dGhlbnRpY2F0ZQ==?=",
"x-powered-by": "ASP.NET",
"date": "Thu, 01 Dec 2016 10:09:11 GMT",
"content-length": "12",
"": ""
}
我試圖讓「令牌」在我的AngularJS代碼,但我不能爲拿到它,爲實現它。我得到空或未定義:
$http.post('http://localhost:37690//api/authenticate', {Username:username,Password:password})
.success(function (response,headers) {
//callback(response);
debugger;
if(response==='Authorized')
{
var hd=headers.common['Token'];
console.log(hd);
}
})
.error(function (err, status) {
console.log(err);
});
我在我的Web API項目中啓用了CORS。下面是我自己寫的WebAPIconfig.cs:
我AuthenticateController類:
using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthenticateController : ApiController
{
[Route("api/authenticate")]
[HttpPost]
public HttpResponseMessage Authenticate(UserLogin user)
{
int UserID = _userService.Authenticate(user);
return GetAuthToken(UserID); ;
}
/// <summary>
/// Returns auth token for the validated user.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
private HttpResponseMessage GetAuthToken(int userId)
{
var token = _tokenService.GenerateToken(userId);
var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");
response.Headers.Add("Token", token.AuthToken);
response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
return response;
}
}
請幫忙爲我怎麼能在我的角度JS最終響應得到頭?
我不明白這一點把它當作一個,你這是在暗示我的代碼更改,讓我找回了頭? –
將您的成功回調替換爲我發佈的回調。標題是一個函數。在你的例子中你喜歡這個「headers.common ..」當你應該調用函數頭() –
@SormitaChakraborty更新我的答案 –