$http data vs params when making POST request - angularjs

Preface: I am using AngularJS 1.5.9.
When writing my service, this code works when posting to the server:
var request = {
url: '/connect/token',
method: 'POST',
data: $httpParamSerializer(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http(request).then(function(response) {});
However, it seems counterintuitive to use data when $http has the usage argument params, with the following definition as per AngularJS's documentation:
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
As you can see, the documentation specifies that this argument is meant to be used only for GET requests. I confirmed as much when I attempted to use the params argument with my POST request:
var request = {
url: '/connect/token',
method: 'POST',
params: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
$http(request).then(function(response) {});
When you submit the POST request in this way, you get the following response from the server:
{
"error":"invalid_request",
"error_description":"A malformed token request has been received: the mandatory 'Content-Type' header was missing from the POST request."
}
In other words, if I don't use the data argument and invoke the param serializer service on the params I want to pass in, my custom service won't set the Content-Type header on my request, I've confirmed this in the network tab of the web inspector.
TLDR; Why do I have to use the data argument and serialize the params instead of just using the params argument directly? And why is the content type I specify ignored when I do use the params argument?

Use params option for GET requests.
With params option you can set URL query string parameters like baseurl.com?myParam=something

Related

Axios multipart request by PUT method

I want to make a put multipart request but it is calling POST even though I tried setting the method to "PUT"
config = {..., method:"PUT"}
axios.request("/getAll", formData, config)
Also, I have a confusion regarding two methods of Axios
Axios.request() and Axios.get()
What is the difference when we call request with method set to GET in config while calling axios.request() and directly calling axios.get()?
Thanks in advance
axios.request takes only 1 argument: config. So you should use:
axios.request({ url: '/getAll', method: 'put', data: formData })
axios.get, axios.put etc are aliases for requests, so you just write less code, because you don't need to specify request's type
axios.put('/getAll', formData)
As a summary, there is no difference between:
axios.request({ url: '/getAll', method: 'get' })
and
axios.get('/getAll')
The second option is just easier and cleaner.

angular: pass additional data with form submit

At the moment i am using below code and it is working fine.
$scope.processForm = function($scope.formData) {
$http({
method : 'POST',
url : 'process.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
Now i have one small requirement. I need to pass user id(uid) along with the form data.
In Jquery it is quite simple but I am new to angular and don't have much experience.
Any advise how i can pass the additional data in Angular.
Thanks
You can encapsulate your formData with your uid parameter togheter in an object expl :
var allData={'formData': $scope.formData, 'uid': $scope.uid}
And then pass in the allData Object to your post method data : allData.
If you encounter any problem getting data in you process.php (undefined data for example), you should let Angular pass data with content type application/json (default behavior of angularjs) and in your process.php you do like this :
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
Note that it will be great if you test with some static values first ( 'uid' : 2 ) to make sure that it works fine
you can send an object (associative array in php ) in $http data parameter:
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'userid':userid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
see https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way for details on how to get data in php side

What is type of data angular sending?

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

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

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