AngularJS $resource not sending custom headers - angularjs

I'm using angular and angular-resource version 1.1.5 and I'm using a $resource to make a request to a REST service. But it seems like the custom headers is not appended to the request. My definition is as below. Is there anything I did wrong?
myApp.factory('User', function($resource) {
var User = $resource('http://localhost\\:7017/mydomain/users/jack', { }, {
get: {
method: 'GET',
isArray: false,
headers: {'X-Requested-By':'abc'}
}
});
return User;
});

Read this to see how to configure default headers in one place: http://docs.angularjs.org/api/ng.$http
EDIT:
Your header must be included in Access-Control-Allow-Headers header in response to the OPTIONS request, which is sent automatically prior to your GET request.

You can modify the default headers inside the $httpProvider.
the headers are an object and separated intocommon, patch, post and put
so if you want to change the default for all your requests, just do a
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';

You have to call get method by using its name, i.e User.get(callback)
It seems that custom headers do not get sent when get method is called with User.query(callback)

Related

How to post a string to a rest service using angularJS

Have been using $resource.save(object); to post my objects to the rest service but this time I don't want the object to be marshalled. I need it to be posted as text/plain.
Is there an easy way of doing this using angularJS?
Solved my problem.
Used the config parameters in the .save or .post functions to set the header content-types.
var config = {
headers : {
'Content-Type': 'text/plain'
}
};
$http.post(theURL, theBody, config)

set header angular http service put

Having difficulty with a temporary work around but the intent was to add to a http put request a header with string value, 'username' : 'flastname'. Within the service that invokes the put call, just before the $http.put call, the username header is to be set.
$http.defaults.headers.post.username = 'flastname';
$http.put('http://localhost:8080/xxxxx-integration/api/claims',claim);
Server side, retrieving a http header 'username' always results in null and in the even stranger behavior than expected category is random numbers of http put calls are generated. Thought I followed the documentation at:
https://docs.angularjs.org/api/ng/service/$http
but maybe read it wrong.
Have you tried the shortcut method? According to the docs, you should be able to do it like so:
put(url, data, [config]);
$http.put('http://localhost:8080/xxxxx-integration/api/claims',claim , {
headers: {'username': 'flastname'}
});
var req = {
method: 'PUT',
url: 'http://localhost:8080/xxxxx-integration/api/claims',
headers: {
'username': 'flastname'
},
data: { test: 'test' } // json for data
}
now just put the req varaible inside $http :)
$http(req).then(function()...)

How to access response headers using $resource in Angular?

I basically call get requests like so:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}).$promise.then(function(data){
console.log(data)
})
This works fine.. but how do I get the response headers?
You could use the transformResponse action defined here this would allow you add the headers
$resource('/', {}, {
get: {
method: 'GET',
transformResponse: function(data, headers){
response = {}
response.data = data;
response.headers = headers();
return response;
}
}
See a working example here JSFiddle
#Martin's answer works for same domain requests. So I would like to add to his answer that if you are using cross domain requests, you will have to add another header with Access-Control-Expose-Headers: X-Blah, X-Bla along with the Access-Control-Allow-Origin:* header.
where X-Blah and X-Bla are custom headers.
Also you do not need to use transform request to get the headers. You may use this code:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}, function(data, headersFun){
console.log(data, headersFun());
})
See this fiddle.
Hope this helps !!!
Old question, but i think it's worth mentioning for the future reference.
There is 'official' solution for this in angular documentation:
It's worth noting that the success callback for get, query and other
methods gets passed in the response that came from the server as well
as $http header getter function, so one could rewrite the above
example and get access to http headers as:
var User = $resource('/user/:userId', {userId:'#id'});
var users = User.query({}, function(users, responseHeaders){
// ...
console.log(responseHeaders('x-app-pagination-current-page'));
});
(code from docs slightly updated for clarity)
For CORS requests, exposing headers as mentioned in other answers is required.

AngularJS $http.post server doesn't allow a request with method OPTIONS

I am trying to do a an HTTP POST to a server.
The data I have to send is a json object.
The problem is that $http.post in angular override the method with options.
I can make this config
.config(['$httpProvider', function ($httpProvider) {
//Reset headers to avoid OPTIONS request (aka preflight)
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
}])
and changes from options to POST, but I can't set the content-type to "application/json", and I am getting a "415 Unsupported Media Type"
Thank you
$http.post in angular doesn't override the method with OPTIONS. It appear that you are trying to call api in different domain than the one your JS code come from. This is called Cross Domain. For such cases the browser performs preflight request with OPTIONS in order to see the returned headers. In your backend response you should add the header Access-Control-Allow-Origin: * for example. When the browser sees that header he performs the actual POST request.
More details here: https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
Hope this is helps!
Add
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
But note this will set the Content-Type header globally.
If you need to set the content-type per call, you should use $http.post like
$http.post("/foo/bar", requestData, {
headers: { 'Content-Type': 'application/json'},
transformRequest: transform
}).success(function(responseData) {
//do stuff with response
});

ngResource Dynamic Header

I'm trying to make a request to an API service that has a dynamic 'authorization' header.
var domain = "http://www.externalapi.com",
actions = {
'login': {
method: 'POST'
},
'objects': {
method: 'GET',
headers: {
'Authorization': Request.getAuthHeader()
}
}
};
var requests = $resource(domain, {}, actions);
requests.objects();
Request is a service I've written that has a method that builds the auth header based on the api requirements, the has it returns is correct.
When looking at the request to domain, however, I see not 'Authorization' header...
I've also tried passing in a static string, still no header.
So the issue was my versions.
After updating Angular to 1.2.0rc1 I left my ngResource module at 1.0.8.
After updating both to 1.2.0rc1 (I assume 1.1.2 would work as well) I was able to assign headers from the actions object of $resource.

Resources