mtsdev mtsdev - 2 months ago 4
AngularJS Question

AngularJs is removing response headers before passing to my controller

Here is the situation:

I made a post request to the server to create an item, and expect it to return "201 Created" with the new item location in the Location Header, where I get it to make a second request and get full item data.

These are the response headers sent by the server:

Status Code: 201 Created
Connection: keep-alive
Content-Length: 17
Content-Type: application/json
Date: Thu, 22 Sep 2016 08:52:20 GMT
Location: /tasks/4
access-control-allow-headers: Content-type, Cache-Control, Keep-Alive, Location
access-control-allow-methods: GET, POST, PUT, DEL, OPTIONS
access-control-allow-origin: *
access-control-expose-headers: Content-type, Cache-Control, Keep-Alive, Location


Then, when I try to get the Location header from My controller, I get:

// console.log(response.headers)
[content-type,] { content-type="application/json; charset=utf-8"}


in my firefox console, and it throws an error if I try to do:

response.headers['Location']


Note: I'm using Angular 1.5.8 and the recommended "Promise" variant for $https

Here is an excerpt of my controller code:

app.controller('NewTaskCtrl', function($scope, $http){
$scope.taskName = null
$scope.createTask = function(){
var data=JSON.stringify( { Name: $scope.taskName} )
$http.post('http://192.168.1.129:9999/api/tasks',data)
.then(
function(response){
// error Here => console.log('Received Headers', response.headers)
console.log('Received Headers', response.headers())
// Error here => $http.get('http://192.168.1.129:9999'+response.headers['Location'])
$http.get('http://192.168.1.129:9999'+response.headers('Location'))
.then (
function(response){
$scope.Tasks.push(response)
},
function(reason){
alert("Unexpected Error Ocurred:\n"+JSON.stringify(reason))
}
)
},
function(reason){
alert("Unexpected Error Ocurred:\n"+JSON.stringify(reason))
}
)
}
})


Any idea of why I'm losing the headers and how I can get them?

EDIT. I commented the offending line and put the correct on its place, for the records

JMK JMK
Answer

Try

response.headers('Location')

Instead of

response.headers['Location']

As headers is a function, not an object.