angularjs $http.post is refusing to use my Content-Type
I am working with a contractor - their team are making server-side APIs while I'm putting together a javascript application using angularjs. They insist on making the api only allow calls with application/x-www-form-urlencoded calls, so I'm trying to figure out how to use $http to make a urlencoded call, and running into problems. All the instruction pages I'm finding seem focused on older versions of angularjs.
I try using the below code:
$scope.makeApiCall = function( ){
var apiData = {
"key1" : "value1",
"key2" : "value2"
};
var apiConfig = {
"headers" : {
"Content-Type" : "application/x-www-form-urlencoded;charset=utf-8;"
}
};
return $http.post('/Plugins/apiCall', apiData, apiConfig)
.then(function(response){
$scope.data=response.data;
});
};
But when I make the call, instead of using the Content-Type I provided, the developer tools report that it uses Content-Type: text/html; charset=utf-8
How do I get my $http.post to send the right Content-Type?
How to POST content as application/x-www-form-urlencoded
Use the $httpParamSerializerJQLike service to transform the data:
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
For more information, see
AngularJS $httpParamSerializerJQLike Service API Reference
Stackoverflow -- URL-encoding variables using only AngularJS services
Related
I'm using angularjs and I'm trying to make a HttpPost call to my web api.
My api method:
[HttpPost]
[Route("authentication/getkey")]
public IHttpActionResult GetKey([FromBody]string password) {
//Do stuff
}
my call:
service.getKey = function (password) {
return $http.post('api/authentication/getkey', JSON.stringify(password))
.then(function(result) {
return result.data;
});
}
Now this works fine, but do I really need to use JSON.stringify? I tried sending it like below, but all of them get password = null. Do I have to use JSON.stringify or am I doing it wrong in my other examples?
//Doesnt work
service.getKey = function (password) {
return $http.post('api/authentication/getkey', password)
.then(function(result) {
return result.data;
});
}
//Doesnt work
service.getKey = function (password) {
return $http.post('api/authentication/getkey', {password})
.then(function(result) {
return result.data;
});
}
If you don't want to use JSON.stringify, the other option will be to send the data as application/x-www-form-urlencoded as pointed in other answer as well. This way you are sending the data as form data. I'm not sure about the syntax of the $http.post Shortcut method but the idea is the same.
service.getKey = function (password) {
$http({
method: 'POST',
url: 'api/authentication/getkey',
data: $.param({ '': password }),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(result) {
return result.data;
});
From Microsoft's Web API official documentation about Parameter Binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
Angular $http service sends Content-Type: application/json as header by default in POST requests, as you can see from the official docs, so Web API is trying to bind your request body using his JsonFormatter. Because of this you have to provide him a well formatted Json string (not a Json Object with a string inside) to correctly bind his raw string parameter.
As a side note, you could also send a request using application/x-www-form-urlencoded as Content-Type header, but then you will have to format your body as form parameters (using something similar to jQuery $.param( .. ))
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"?
What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.
I want to write a wrapper service to the existing angular $resource service such that some custom headers are added to the http request by default. I am aware that we can set common headers using $httpProvider.defaults.headers.common. But this way all my requests would have this header and that is not what I want.
It would be lot more cleaner if the $resource service could be extended into a wrapper service in which I can define these common headers. This way I could selectively use this wrapper service wherever the common headers need to be added.
This may not be the answer you're looking for but I will share my thoughts. I'm using angular $http. The way I do it is I specify the correct header in every api call.
Something like this:
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
},
uploadAvatar: function(email_address, fd) {
return $http({
method : 'POST',
url : api + 'player/' + email_address + '/avatar',
data : fd,
withCredentials: true,
headers : {'Content-Type' : undefined, 'X-Token' : credential.token},
transformRequest: angular.identity //awesome! automatically set to the correct header request
});
},
fbLogin: function(data) {
var xsrf = $.param({fb_access_token: data});
// console.log(postData);
return $http({
method : 'POST',
url : api + '/user/v1/login',
data : xsrf,
headers : {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
});
}
I'm not an expert in angular but this is the way I do it. Hope it helps :)