Как я могу читать заголовки, отправленные из моего API с помощью angular?
У меня есть что-то похожее на следующий код на domain.com
:
$http.post("http://api.domain.com/Controller/Method",
JSON.stringify(data),
{
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response);
}, function (response) {
// something went wrong
});
}
Он отлично работает с моим .NET API. response.data
имеет все данные, которые мне должен дать мой сервер. Однако у нас есть новый токен безопасности, который мы передаем клиенту из API, и мы передаем его обратно клиенту в заголовке пакета. Я знаю, что токен передается обратно, потому что я могу прочитать его в пакете на вкладке сети в хром-отладчике. Однако response.headers()
содержит только content-type:"application/json; charset=utf-8"
Он не имеет того, что находится в пакете. У кого-нибудь есть идея?
Данные возвращаются из API так (С#)
HttpContext.Current.Response.AppendHeader("session",Guid.NewGuid().ToString());
Поэтому я ожидал бы, что response
будет иметь заголовок с именем session
, но это не так. Однако он находится в пакете.
Ответы
Ответ 1
Используйте переменную заголовков при успешном выполнении и обратные вызовы
$http.get('/url').
success(function(data, status, headers, config) {
//things to do
})
.error(function(data, status, headers, config) {
//things to do
});
Ответ 2
Существует два способа обработки вызова $http
, т.е. .success
и .then
. Но с давным-давно использование метода Angular устарело, поэтому рекомендуется использовать .then
. вопрос здесь - демонстрация простого вызова GET
$http.get('test.json').then(function(response) {
$scope.collection = response.data.Collections;
console.log(response);
console.log( response.headers());
});
в этом я установил токен аутентификации для проверки запроса
$http.defaults.headers.common['Auth-Token'] = '1234';
, но если я делаю console.log(response.headers()), он выглядит ниже
cache-control : "no-cache"
cf-ray : "2e3a4163cdf43084-SIN"
content-encoding : "gzip"
content-type : "application/json; charset=utf-8"
date : "Sat, 17 Sep 2016 05:46:02 GMT"
etag : ""1ae47a56e2b2ea9ddc982cc0e61e469a-static-gzip""
server : "cloudflare-nginx"
status : "304"
vary : "accept-encoding"
x-xss-protection : "0"
Это не показывает токен аутентификации, но в ответе есть также объект с именем config
, который также имеет объект headers
, который содержит мой токен аутентификации. Следуя этому шаблону, надейтесь, что этот подход даст вам новый просмотрите выражение о проблеме.
config : Object
L-> headers: Object
L-> Accept : "application/json, text/plain, */*"
Auth-Token : "1234"
Ответ 3
Использовать метод заголовков, возвращенный при успешном обратном вызове.
$http.get('/url').
success(function(data, status, headers, config) {
response.headers = headers();
console.log(response.headers, response.headers['auth_token']);
})
.error(function(data, status, headers, config) {
//things to do
});
Не забудьте вызвать заголовки().
Ответ 4
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code.
Ответ 5
$http.post("http://api.domain.com/Controller/Method",
JSON.stringify(data),
{
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response);
//this will get you session header information
console.log( response.headers('session'));
}, function (response) {
// something went wrong
});
}