Angular POST and Web API - angularjs

My code is as the following:
var response = $http({
method: 'post',
withCredentials: true,
dataType: "json",
data: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
url: url
});
where payload looks like this:
{"CASEID":3,"CASENUMBER":"ANY ","TITLE":"ANY "}
Backend code:
public CL_CASE Post([FromBody]CL_CASE value)
{....
When running it as it's shown value is null.
If I change headers to 'Content-Type': 'application/x-www-form-urlencoded' then I do get value but with properties equal to null/0 . What am I doing wrong?
Thanks

You don't need to call JSON.stringify. This results in sending a string to the server, not an object. And since the WebAPI model binder is expecting a CL_CASE object, it has no way to populate that object from just a string.
Simply send the object itself:
data: payload
To be honest, I don't think you need the headers option at all in this case either. Let the default functionality handle it:
$http({
method: 'post',
withCredentials: true,
dataType: 'json',
data: payload,
url: url
})

Related

How to specify datatype and contentType in $http requests in AngularJS

I'd don't find on the internet how can I pass datatype and contentType to a shortcut request in AngularJS.
Exemple :
$http.get('url',{
headers:{'header1':'value'}
})
Second question : Can I send the header with this kind of code ?
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + Api.getToken());
}
You can add a content type like this, but for this you also need to specify data in the request also
return $http({
method: 'POST',
//withCredentials:true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: data,
url: yourUrlHere
});
data can be an empty string but with if you are not adding data it will not set the content-type
For short post method you can do it like this
$http.post('/someUrl', data, {headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}}).then(successCallback, errorCallback);

Angular Ajax call being sent as request payload but not formdata after fixing

Ok, I've tried looking at this How can I post data as form data instead of a request payload?
However, I still can't seem to send my request properly. Here are the details.
$scope.myData = {a: 123, b: 456};
$http({
url: 'myfile',
method: "POST",
data: JSON.stringify($scope.myData),
headers: {'Content-Type': 'application/json'}
})
This keeps being sent as request payload. Any ideas?
When I use 'application/x-www-form-urlencoded' The formdata is used however it is not parsed properly and the whole json is just one string when I look in the Chrome console.
$http provides an option : params.
Use params: instead of data:
$http({
url: 'myfile',
method: "POST",
params: JSON.stringify($scope.myData),
headers: {'Content-Type': 'application/json'}
})

How do I send multiple headers with angularJS resource?

Trying to send multiple headers in the same request with angularJS this is what I have...
var auth = $resource("",
{},
{
GetUserDetails: {
url: Config.api.user.details(),
method: 'POST',
isArray: false,
cache: false,
headers: ["xx:xx","ff:ff"]
}
});
But the request just shows...
0:xx:xx
1:ff:ff
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Anyone know the right data structure to send a collection of headers down in the headers property on the resource?
Straight from the documentation:
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.
So what you need is:
headers: {
headerName1: 'headerValue1',
headerName2: 'headerValue2'
}
Have you tried setting it up as
var auth = $resource("",
{},
{
GetUserDetails: {
url: Config.api.user.details(),
method: 'POST',
isArray: false,
cache: false,
headers: [{'xx':'xx'},{'ff':'ff'}]
}
});

set default/additional payload in ngResource

I have following resource defined as a service named 'User':
return $resource('/user', {}, {
login: {
url: 'user/login',
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
});
and I can use it for logging in inside controller as follows:
User.login({
Password: $scope.password,
UserName: $scope.name,
OsModel: Os.model,
OsVersion: Os.version
});
(Os is another service providing some values).
the problem is that this resource is gonna be used in some other controllers too and I dont want to set irrelevant values like OsModel and OsVersion all around and inside different controllers, so the idea is to set those two values inside service where the resource has defined the login action to some default values so that they will be set inside payload body.
I have tried to use the params key but it sends those values as query parameters and does not add them to the request payload and I did not find anything else in angular docs. Is there any way to do so in angular?
I'm using the angular v 1.2.11.
ok I ended up using the transformRequest on the $resource definition, something like bellow:
return $resource('/user', {}, {
login: {
url: 'user/login',
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accepts': 'application/json'
},
transformRequest: function(data) {
data.OsModel = Os.model;
data.OsVersion = Os.version;
return JSON.stringify(data);
}
}
});
not sure if thats the most elegant way but this is working for me.

backbone.js error when using fetch but not $.ajax()

I am having some trouble fetching a collection. I'm using the console's network inspector to see if I can figure out what's wrong and the only thing I see is the format of the Request Payload.
When making a .fetch() the Request Payload is being sent in this format:
query=this+is+my+query
This returns a 400 Bad Request status from my server. I have tested using:
$.ajax({
contentType: 'application/json',
async : false,
type:'POST',
url: '/search',
data: JSON.stringify({"query":"this is my query"}),
dataType: 'json',
success: function(data) {
alert('yup');
},
error: function(data) {
alert('nope');
}});
which returns my data as expected. In this case the Request Payload is in this format:
{"query":"enterprise search is gonna rock","scope":null}
I've tried passing in headers with my fetch:
my_results.fetch({data:{"query":"this is my query"}, type: 'POST', dataType: 'json', contentType: 'application/json'});
Here is what my Model and Collection look like:
EnterpriseSearch.Result = Backbone.Model.extend();
EnterpriseSearch.Results = Backbone.Collection.extend({
model: EnterpriseSearch.Result,
url: "/search"
});
Any help would be appreciated.
Try using data: JSON.stringify({"query":"this is my query"}) in your fetch options, just like you do when using $.ajax. jQuery will default to application/x-www-form-urlencoded for form data.

Resources