angular.js $resources setting Authorization header - angularjs

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?

Related

cors-anywhere.herokuapp status of 400 (Header required) [duplicate]

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
});

AngularJS post request. Character changed from initial value

I have this very strange problem. I have a very long string as a token for an app. When i`m doing the http post request, the string changes.
From the ending of "Vow== 256220" it is changing to "Vow: = 256220" and i do not understand why.
Here is the code if helps:
var request = $http({
method: "post",
url: urlWS,
data: {token: token},0
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
request.success(function (data) {
alert(data);
});
Following code working for me.
$http({
method: "post",
url: urlWS,
data: 'token='+encodeURIComponent("Vow== 256220"),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
request.success(function (data) {
alert(data);
});
May be above solution solve your problem.
You will have to configure $httpProvider in your main module config function. This is been done with transformRequest method by firstly adding the default header you have added and then transforming the request.
Add the following code to you main config function module:
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// post headers
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? $.param(data) : data;
}];
I hope it helps ;)

how to send x-www-form-urlencoded data using ngResource module with angular?

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' } }
});
}]);

$http Post to php backend, but the server side gets nothing

I'm learning AngularJS, and trying to post dump data to the php backend using the coding below.
angular.module('app.customerModule', [])
.factory('customerFactory', function($scope, $http) {
return {
var customer = {customer: '1234'};
httpNewCustomer: function(callback) {
$http.post('http://domain.local/customer_new.php', )
.success(function(data) {
})
}
}
})
.controller('customerController', function($rootScope, $scope, customerFactory) {
$scope.newCustomer = function() {
customerFactory.httpNewCustomer(function(dataResponse) {
});
}
});
Unfortunately at the server side gets nothing for $_POST;
This is what the http header looks like.
I also tried with this alternative coding
httpNewCustomers: function(callback) {
var postData = {customer: '2345'};
$http({
method: 'POST',
url: 'http://domain.local/customer_new.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
})
.success(function(data) {
})
}
This is what the http header looks like.
When I tried with jQuery using this coding, everything is just fine.
var postData = {customer: '3456'};
$.ajax({
type: 'POST',
url: 'http://domain.local/customer_new.php',
dataType: 'json',
data: postData,
success: function(data) {
// console.log(data);
}
});
Please help me config the $http to post the data to the php backend.
angular by default only supports a json request transformer. as you can see, both your angular requests have data, but they are json. You either need to change the server so it can parse json, or add a request transformer so the data is in form-encoded format.
You can read more about $http transformers here: https://docs.angularjs.org/api/ng/service/$http

AngularJS - $resource different URL for Get and Post

$resource is awesome providing very convenient way to handle web services.
What if GET and POST have to be performed on different URLs?
For example, GET URL is http://localhost/pleaseGethere/:id
and POST URL is http://localhost/pleasePosthere without any parameter
Use 'url' property of [actions] to override the default url.
$resource(url, [paramDefaults], [actions], options);
for example:
$resource('http://localhost/pleaseGethere/:id',{},{
getMethod:{
method:'GET',
isArray:true
}
postMethod:{
url:'http://localhost/pleasePosthere',
method:'POST',
isArray:false
}
}
Usage of Angular $resource: http://docs.angularjs.org/api/ngResource/service/$resource
You should be able to expose the URL as a parameter. I was able to do this:
$provide.factory('twitterResource', [
'$resource',
function($resource) {
return $resource(
'https://:url/:action',
{
url: 'search.twitter.com',
action: 'search.json',
q: '#ThingsYouSayToYourBestFriend',
callback: 'JSON_CALLBACK'
},
{
get: {
method: 'JSONP'
}
}
);
}
]);
Then you can overwrite the URL on your GET call.
The one caveat I found during my REALLY brief testing was that if I included http:// in the URL string, it didn't work. I didn't get an error message. It just did nothing.
If you add the hash with param names into the $resource call:
$resource('localhost/pleaseGethere/:id', {id: '#id'});
Then the :id will be mapped to id param when invoking the function (this will call GET localhost/pleaseGethere/123):
Resource.get({id: 123});
For POST, you simply don't assign the id param:
Resource.post({}, {name: "Joe"});
The proper URL will be called, which is in this case POST localhost/pleaseGethere (the trailing slash is stripped by ngResource).
See http://docs.angularjs.org/api/ngResource.$resource -> Examples -> Credit card resource for more details.
In addition to Iris Wong's answer, I wanted to give an example of having multiple params with multiple methods and actions:
angular
.module('thingApp')
.factory('ThingResource', ['$resource', '$state', returnThing]);
And the resource:
function returnThing($resource, $state) {
var mainUrl = '/api/stuffs/:stuffId/thing'
var params = {stuffId: '#_id', thingMongoId: '#_id', thingNumber: '#_id'}
return $resource(mainUrl, params, {
'save': {
url: '/api/stuffs/:stuffId/thing/:thingMongoId',
method: 'POST',
interceptor: {
responseError: function(e) {
console.warn('Problem making request to backend: ', e)
$state.go('oops')
}
}
},
'get': {
url: '/api/stuffs/:stuffId/thing/:thingMongoId',
method: 'GET',
interceptor: {
responseError: function(e) {
console.warn('Problem making request to backend: ', e)
$state.go('oops')
}
}
},
'assignThing':{
method: 'POST',
url: '/api/stuffs/:stuffId/thing/assign/:thingNumber'
}
});
}
Which gives 3 separate methods:
// POST to http://currnt_base_url/api/stuffs/:stuffId/thing/:thingMongoId
ThingResource.save({
stuffId:'56c3d1c47fe68be29e0f7652',
thingMongoId: '56c3d1c47fe6agwbe29e0f11111'})
// GET to current http://currnt_base_url/api/stuffs/:stuffId/thing/:thingMongoId
ThingResource.get({
stuffId:'56c3d1c47fe68be29e0f7652',
thingMongoId: '56c3d1c47fe6agwbe29e0f11111'})
// POST to http://currnt_base_url/api/stuffs/:stuffId/thing/assign/:thingNumber
ThingResource.assignThing({
stuffId:'56c3d1c47fe68be29e0f7652',
thingNumber: '999998'})
Follow this way:
(function () {
'use strict';
angular
.module("app")
.factory("SomeFactory", SomeFactory);
function SomeFactory($resource) {
var provider = "http://stackoverflow.com/:action/:id";
var params = {"id":"#id"};
var actions = {
"create": {"method": "POST", "params": {"action": "CreateAwesomePost"}},
"read": {"method": "POST", "params": {"action": "ReadSomethingInteresting"}},
"update": {"method": "POST", "params": {"action": "UpdateSomePost"}},
"delete": {"method": "GET", "params": {"action": "DeleteJustForFun"}}
};
return $resource(provider, params, actions);
}
})();
I hope it help! Enjoy!

Resources