send request without adding header in angular js - angularjs

i'm trying to sending request to third party service. for that i need to delete default header 'x-access-token'. For that did like below
$http({
url: 'http://ip-api.com/json',
method: 'GET',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
delete headers['x-access-token'];
return headers;
}
}).then(function(res){
console.log(res);
},function(error){
console.log(error);
});
By following this link .
But i'm getting this error
TypeError: Cannot convert object to primitive value
at angular.js:10514
at sendReq (angular.js:10333)
at $get.serverRequest (angular.js:10045)
at processQueue (angular.js:14567)
at angular.js:14583
at Scope.$get.Scope.$eval (angular.js:15846)
at Scope.$get.Scope.$digest (angular.js:15657)
at Scope.$get.Scope.$apply (angular.js:15951)
at done (angular.js:10364)
at completeRequest (angular.js:10536)

"transformRequest" does not work the same way to remove headers for individual requests past angularjs 1.4 release .From the documentation its clear that we should be using "headers" instead
eg:
$http({method: 'GET',
url: "url",
headers: {
'header-name': undefined
}
}).success(function(data){console.log(data)});

The $http service config object allows you to override the http header send for a specific request. See config property headers.
To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, Use the headers property, setting the desired header to undefined.
NOTE: Set the desire header/headers to undefined like this, then it will not affect the global settings.
See example:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
See more documentation.
This can take a list of headers or a function that return a list of headers. So for the non auth header request make a copy of the default headers remove the header you don't require and then make the request.
Hope this help well.

Related

$http header 'Content-Type' not appending in the header - AngularJS

I'm using $http to do a GET request and I wanted to append 'Content-Type': 'application/json' in the header. If I don't append this header 415 (Unsupported Media Type) error is thrown.
I'm using Apache 2.2.13 with ProxyPass, in which I DO NOT say
RequestHeader append Content-Type "application/json". However if I put the RequestHeader configuration in apache $http.get works fine and the 'Content-Type' is also appended.
Scenario 1 :
Using $http, trying GET request
Request :
$http({
method: 'GET',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Chrome Network Tab :
Scenario 2 :
Using Restangular, trying the same GET request
Request :
Restangular.setDefaultHeaders({'Content-Type': 'application/json'})
Restangular.setBaseUrl('/items')
Restangular.all('').getList({customerId: '103020'}, {'Content-Type': 'application/json'});
Chrome Network Tab :
The other interesting part here is, when I do some mistakes on the Request Header like,
Restangular.setDefaultHeaders({'Contentttt-Type': 'application/json'})
and try Scenario 1, I notice the following in the Chrome Network Tab.
Scenario 3 :
Using jQuery ajax, trying the same GET request
Request :
$.ajax({
url: "/items/?customerId=103020",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Content-Type', 'application/json');},
success: function() { alert('Success!'); }
});
Chrome Network Tab :
Questions :
Is it necessary to add RequestHeader append Content-Type "application/json" in Apache configuration? But if I add that I get 415 errors on POST requests.
What is the problem with AngularJS and Restangular that it won't append Content-Type headers to its network calls on GET?
What is the best solution to solve this? I have tried out all the combinations but no luck!
Versions :
Angular : 1.2.22
Restangular : 1.4.0
On the one hand, with the $http service, you can override or add your headers using $httpProvider when calling the config method on your module :
module.config(function($http) {
$httpProvider.defaults.headers.get = { 'Content-Type : 'application/json' };
});
On the other hand, with the GET method, if your API is really RESTFull, only the Accept header should be set since you are not sending JSONdata.
Thus, use the above code for your PUT/POST methods and force the Accept header for the GETmethod:
module.config(function($http) {
$httpProvider.defaults.headers.post = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.put = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.get = { 'Accept : 'application/json'};
});
EDIT 1:
If you want to force the content-type in a GET request, you have to add a blank data :
$http({
method: 'GET',
data:'',
dataType:'json',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Setting a Content-Type header field on an HTTP request that doesn't have a request body (such as GET) is non-sense.
Maybe what you really want is set "Accept"?

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()...)

AngularJS $http POST request different results with then and success

Something is driving me nuts; maybe someone can help me out with the following? :
I am using AngularJS 1.2.26 (have to because IE8 needs to be supported)
I have to invoke some backend services that were initially build for a backbone frontend. I managed to do that in the following way:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: this._transformRequest,
data: formData
})
.success(function (data) {
// bla bla not relevant
}).error(function (error) {
// bla bla not relevant
});
Now i try to work with the then function as i find that more consequent, so i change the code into:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: this._transformRequest,
data: formData
}).then(
function (response) {
// not relevant
}, function (error) {
// not relevant
});
According to me, in theory this should have the same result as the initial implementation, however to my surprise the request now fails on the server. While debugging I noticed that the result of the transform request function delivers a very different result in both scenario's in the request that is handled with success and error the result of transform request is as follows:
com.bank.token.session=XXXXX&model=%7B%22relatieRol%22%3A%22AANVRAGER%22%2C%22evaUitgevoerdDat%22%3Anull%2C%22sfhUitgevoerdDat%22%3Anull%2C%22bkrUitgevoerdDat%22%3Anull%2C%22bkrBekendCd%22%3A%22GOED_BEKEND%22%7D
When i use the 'then' function as the way to handle the result the transformRequest function returns the following (wrong) result:
com.bank.token.session=XXXXXXXXXXX&model=%7B%22data%22%3A%7B%22relatieRol%22%3A%22AANVRAGER%22%2C%22evaUitgevoerdDat%22%3Anull%2C%22sfhUitgevoerdDat%22%3Anull%2C%22bkrUitgevoerdDat%22%3Anull%7D%2C%22status%22%3A200%2C%22config%22%3A%7B%22method%22%3A%22POST%22%2C%22transformResponse%22%3A%5Bnull%5D%2C%22url%22%3A%22http%3A%2F%2Flocalhost%2Femployee%2Findex.html%2Ffoo-web%2Fxchannel-foo-secure-portlet%2F1598792178%2Fver%3D2.0%2Fresource%2Fid%3Dfoo-fetch-%2Frparam%3Dportal%3DfooPortal.wsp%22%2C%22headers%22%3A%7B%22Content-Type%22%3A%22application%2Fx-www-form-urlencoded%22%2C%22Accept%22%3A%22application%2Fjson%2C%20text%2Fplain%2C%20*%2F*%22%7D%2C%22data%22%3A%7B%22com.bank.token.session%22%3A%22XXXXXXXXXX%22%2C%22model%22%3A%22%7B%5C%22relatieRol%5C%22%3A%5C%22AANVRAGER%5C%22%7D%22%7D%7D%2C%22statusText%22%3A%22OK%22%2C%22bkrBekendCd%22%3A%22GOED_BEKEND%22%7D
This really surprises me; how can the handler on the $http service influence the way the request is handled? I would like to use 'then' for handling my $http POST; but it seems not to work. Anybody knows why? Many thanks in advance!
my transformRequest function looks like this:
_transformRequest: function (obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
console.log('transform: ', str.join("&"));
return str.join("&");
}
success and error unpack the data property of the response for you (as well as route to the pretty names). So, if you change to then you need to manually address the data property of the response in order to get the same information:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: this._transformRequest,
data: formData
}).then(
function (response) {
var data = response.data;
// not relevant
}, function (error) {
var data = error.data;
// not relevant
});
Here is the relevant part in the $http documentation:
Returns a promise object with the standard then method and two http
specific methods: success and error. The then method takes two
arguments a success and an error callback which will be called with a
response object. The success and error methods take a single argument
- a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are
destructured representation of the response object passed into the
then method. 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.
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.1

Set defaults header on AngularJS but don't use it on one specific request

For sending OAuth2 token I am setting up defaults header on AngularJS like this:
$http.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
This works great but I don't need this header (I get an error) for one specific request.
Is there a way of excluding defaults header when performing that request?
Thanks!
SOLVED
Thanks to Riron for getting me on a right path. Here's the answer:
$http({
method: 'GET',
url: 'http://.../',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
delete headers['Authorization'];
return headers;
}
});
When you make your call with $http, you can override defaults headers by providing them directly in your request config:
$http({method: 'GET', url: '/someUrl', headers: {'Authorization' : 'NewValue'} }).success();
Otherwise you could transform your request using the transformRequest parameter, still in your $http config. See doc :
transformRequest – {function(data,headersGetter)|Array.<function(data, headersGetter)>} – transform
function or an array of such functions. The transform function takes
the http request body and headers and returns its transformed
(typically serialized) version.
This way you could delete an header for a single request before it's being send:
$http({method: 'GET',
url: '/someUrl',
transformRequest: function(data,headersGetter){ //Headers change here }
}).success();
For latecomers, whilst the solution might have worked - you actually shouldn't need to use transformRequest for this.
The Angular docs for the $http service actually have this exact situation covered:
To explicitly remove a header automatically added via
$httpProvider.defaults.headers on a per request basis, Use the headers
property, setting the desired header to undefined.
For example:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: {
test: 'test'
}
}
$http(req).success(function(){...}).error(function(){...});
Angular 1.4.0 can no longer modify request headers using transformRequest:
If one needs to dynamically add / remove headers it should be done in
a header function, for example:
$http.get(url, {
headers: {
'X-MY_HEADER': function(config) {
return 'abcd'; //you've got access to a request config object to specify header value dynamically
}
}
})
While the $httpProvider can override $http the use of intereceptors are 1 way of handling this, I end up doing it this way
function getMyStuff(blah) {
var req = {
method: 'GET',
url: 'http://...',
headers: {
'Authorization': undefined
}
}
return $http(req)
.then(function(response) {
return response.data;
});
}

AngularJS $resource not sending custom headers

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)

Resources