with $http, we can do this:
var config = { headers: { 'something': 'anything' } };
$http.get('url/to/json', config)
.success(function() {
// do something…
})
i would like to do the same with a $resource reference (not working):
var config = { headers: { 'something': 'anything' } };
MyResource.get(
config,
function() { // success
// do something…
}
);
with the corresponding service declared like this :
.factory('MyResource', function($resource){
return $resource('url/to/json');
})
it's not working : the config object goes to the url and not in the http headers.
Is there a way to do that ?
headers for $resource is available since AngularJS 1.1.1. Make sure you have correct version used.
The format is
$resource('url/to/json', {}, {headers: { 'something': 'anything' }});
[edit by zuma]
The above doesn't seem right. The third parameter to $resource should be a different. This seems more correct to me:
$resource('url/to/json', {}, {
get: {
method: 'GET',
headers: { 'something': 'anything' }
}
});
The headers object inside a resource action supports both static values for its fields, but also dynamic values returned from a function.
$resource('url/to/json', {}, {
get: {
method: 'GET',
headers: {
'header_static': 'static_value',
'header_dynamic': dynamicHeaderVal
}
}
});
function dynamicHeaderVal(requestConfig){
// this function will be called every time the "get" action gets called
// the result will be used as value for the header item
// if it doesn't return a value, the key will not be present in the header
}
Demo Code
angular.module('Test',['ngResource'])
.controller('corsCtrl', function ($scope, $http, MyResource) {
$http.defaults.headers.common['test']= 'team'; //Using $http we can set header also
MyResource.get();
})
.factory('MyResource', function($resource) { //Services
return $resource('url/to/json');
})
JsFiddle DEMO
see in Request Header
To use "Content-Type" header you may need to specify a data body at least for versions around 1.4.7+ due to $http deleting headers without a data body that are === 'content-type'. See #10255 in 1.4.7/angular.js
I just set "data: false" to spoof it, without specifying a data body:
$resource('url/to/json', {}, {
get: {
method: 'GET',
data: false,
headers: { 'something': 'anything' }
}
});
You can set dynamic one-off headers by accessing the config API object in the resource
Demo Code
angular.
.factory('Resource',['$resource',function($resource){return $resource(baseUrl+'/resource/:id', {id: '#_id'}, {
update : {
method : 'POST',
url : baseUrl+'/resource/:id',
headers : {
'custom-header': function(config) {
// access variable via config.data
return config.data.customHeaderValue;
}
},
transformRequest: function(data) {
// you can delete the variable if you don't want it sent to the backend
delete data['customHeaderValue'];
// transform payload before sending
return JSON.stringify(data);
}
}
});
}]);
To execute
Resource.update({},{
customHeaderValue: setCustomHeaderValue
},
function (response) {
// do something ...
},function(error){
// process error
});
Related
I want to send the same url param on all requests either it's get or post request, like this:
?region=us&toolName=abc
Is it possible by using AngularJS interceptor? Or is there other better way?
Thanks for your help.
Using an httpInterceptor would be best then you can check if other params already exist and extend them...or only use the ones shown
The AngularJS $http method lets you specify your HTTP request verb as well as such parameters via the config object which can contain a params object, which can be something like { region: "us", toolName: "abc" } which in turn becomes a query string. Example use:
$http({ url: "test.aspx", method: "GET", params: { region: "us", toolName: "abc" } }).then(
function(response){
alert("success!");
}, function(response){
alert("failure.");
}
Create a service to set default params request:
'use strict';
var ParamsService = function() {
return {
set: function (params) {
var defaultParams = {
region: 'us',
toolName: 'abc'
};
// Use any function to extend objects (currently, I'm using lodash)
return _.extend(defaultParams, params);
}
};
};
ParamsService.$inject = [
];
Request:
$http({
url: 'url.json',
method: 'GET',
params: ParamsService.set({otherProperty: otherValue})
})
.then(
function (data) {
},
function (error) {
}
);
It not good solution, but can help your case :)
$httpProvider.defaults.headers.common['key'] = 'value'
Hey I want to change the data before sending it with ngResource (build FormData object). I do everything as in the examples that I found, however I can't make them work. Here is my code:
My controller where I set the data and try to send them:
var vm = this;
vm.application = new Application();
vm.application.title = 'Test title';
Application.save({}, vm.application, function(){
});
My service:
function application(ApiBaseUrl, $resource) {
var actions = {
'save': {
metod: 'POST',
url: ApiBaseUrl + "/applications",
headers: { 'Content-Type': false },
transformRequest: function (data) {
console.log(data); //Returns 'undefined'
return data;
}
}
};
return $resource(ApiBaseUrl + "applications/:id", {}, actions);
}
In the function transformRequest data object is always marked as 'undefined'. Am I doing something wrong? Is there a better way to edit the data before sending it?
The problem was I had
metod: 'POST'
when I should have used:
method: 'POST'
everything lives in the title.
when producing a resource in angular :
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
and using in a controller :
MyResource.save({att: att, att2: att2});
the Service sends the data in a json artifact ahead to the server.
I need to send the data in a x-www-form-urlencoded shape.
Where ought I modify my code to resolve that ?
Should pass the headers parameters
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
then serialize your data before sending them with $httpParamSerializer
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
I finally found myself:
When defining a resource and the associated instruction, the "headers" parameter comes in hand.
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);
I have a need to transform response from service on each get, save, update. I've created a resource and added a transformer that gets executed, but the structure of object being returned is not the same as when I don't use transformer. Here I am talking about the structure of the response, not the object I am transforming.
Here is my resource:
angular.module('app')
.factory('Insureds', ['$resource', 'config', function ($resource, config) {
function transform(response) {
var insured = response.data.insured;
return response;
}
var memberServicesHostName = config.memberServicesHostName;
return $resource(memberServicesHostName + '/insureds/:insuredId', null,
{
'get': {
method: 'GET', 'withCredentials': true, interceptor:
{
response: function (response) { return transform(response).data; }
}
},
'update': { method: 'PUT', 'withCredentials': true },
'save': { method: 'POST', 'withCredentials': true }
});
}]);
When I don't use transformer "insured" is on the first level when the promise gets resolved it resolves as an instance of insured object. But with transformer there is wrapper object, that contains insured and responseStatus properties. It probably has to do with what I am returning from the "reponse" in the interceptor. What should one return, original response, like I am doing, or response.data, or response.resource.insured? I am confused...
The default response interceptor is like this:
function defaultResponseInterceptor(response) {
return response.resource;
}
Therefore, if you would like to preserve the default behaviour, you have to return response.resource instead of response.data:
return $resource(memberServicesHostName + '/insureds/:insuredId', null, {
get: {
method: 'GET',
withCredentials: true,
interceptor: {
response: function (response) {
return transform(response).resource;
}
}
},
...
Hope this helps.
js
what I'm trying to do is making REST API REQUEST to server.
A request should be 'GET' method and include 'Authorization' header.
my factory code which communicate REST server is like this
'use strict';
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '#url', id: '#id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get: {
method: 'GET',
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
params: {
url:"users",
id:'me'
}
}
});
the fitst problem is here
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
If I add header the method changes to 'OPTIONS' not 'GET'. I found out it's about CORS preflight something, but I couldn't figure it out how to disable it..
so I tried to change my configuration in app.js
.config(function($locationProvider, $routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
the second problem is here
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
It makes the error below.
Cannot set property 'Authorization' of undefined
Is there any solution to send A 'GET' request with 'Authorization' header?
thanks
I think you're using params in the wrong way in your get request. Try switching params and headers like that :
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '#url', id: '#id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get_auth: {
method: 'GET',
params: {
url:"users",
id:'me'
},
headers: {'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'}
}
});
I changed your custom get request because 'get' might be defined by angular already, but I'm not sure :
$httpProvider.defaults.headers.get_auth['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
Besides, are you sure you don't need any other headers?