如何从angularjs中的POST API读取位置头?
我的post方法如下:如何从angularjs中的POST API读取位置头?,post,angularjs,http-headers,Post,Angularjs,Http Headers,我的post方法如下: public HttpResponseMessage AddUser(User user) { UserManager userManager = new UserManager(); try { userManager.Create(user); var savedUser = userManager.FindUserByClientId(user.Clie
public HttpResponseMessage AddUser(User user)
{
UserManager userManager = new UserManager();
try
{
userManager.Create(user);
var savedUser = userManager.FindUserByClientId(user.ClientId);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = savedUser.Id }));
return response;
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
在angular中,我试图读取位置标题,但到目前为止我仍然无法读取
return $http.post('http://localhost:30028/api/values/adduser', user)
.success(function (data, status, headers, config) {
alert(angular.toJson(data));
alert(angular.toJson(status));
alert(angular.toJson(headers));
alert(angular.toJson(config));
};
我只是检查其中每一个的内容,没有一个有位置标题。有没有办法从角度访问location标头,以便我知道新对象的url?,headers
对象实际上是一个返回标头的函数,如下所示:
.success(函数(数据、状态、标题、配置){
警报(标题(“位置”);
});
如果需要所有标题的集合,可以执行以下操作:
.success(函数(数据、状态、标题、配置){
log(headers());
});
注意:如果您的服务器将响应代码设置为301
或302
,您将无法获取位置
头,因为它后面会自动透明地跟随XMLHttpRequest对象
因此,请确保您正确设置了响应代码。我在PHP中测试了这一点(我不经常使用PHP),但忘记了设置位置标题会自动设置响应代码。为了测试这一点,我必须使用:
header('Location: blah-blah', true, 200);
这是我的工作代码示例,只需将其保存到php服务器上的location test.php
,然后运行它:
//
位置标头:{{loc}
由于$http中不推荐使用.success()
,并将其替换为更新,因此此答案是直接对注入到承诺中的响应调用标题
$http.post('http://localhost:30028/api/values/adduser', user)
.then(function (response) {
alert(angular.toJson(response.headers));
//or
alert(response.headers('Location'));
});
这不会破坏HTTP吗?米凯尔·奥斯伯格(MikaelÖstberg)说,位置不应该与200秒相配,而应该与202s相配。