AngularJS $http.post with body AngularJS $http.post with body json json

AngularJS $http.post with body


Have you tried without shorthand version of $http?I think your code will work if you use something like

$http({  method: 'POST',  url: url,  data: JSON.stringify(data)}).then(function (success) {  callback(success);}, function (error) {  errorCallback(error.data);});

where

data = {     "employeeId":5,     "priorityId":1,     "creationDate":1449677250732,     "userId":1,     "information": "hello world!",     "latitude":<some valid location>,     "longitude":<some valid location>}

Further reading...


Updated code

After changing the $http.post:

httpService.createInBackend = function (url, data, callback, errorCallback) {    http.post(url, data)           .then(function (success) {              callback(success);           }, function (error) {              errorCallback(error.data);           });};

to standard $http type of angular:

$http({    method: 'POST',    url: url,    data: data}).then(function (success) {    callback(success);}, function (error) {    errorCallback(error);});

The sending of my data in the body still did not work.


Solution

The problem with this standard way of the $http request is that it does not accept an object like:

data: {        {        "incidentTypeId": 5,        "priorityId": 1,        "creationDate": 1449676871234,        "userId": 1,        "latitude": <some valid location>,        "longitude": <some valid location>        }    },    timeout: 4000}

I had to change this to:

var incidentInformation = {    incidentTypeId: $scope.selectedIncident.id,    priorityId: $scope.priorityId,    information: $scope.information,    creationDate: Date.now(),     userId: JSON.parse(localStorage.getItem('user')).id,     latitude: location.latitude,     longitude: location.longitude       };

and add a new line:

incidentInformation = JSON.stringify(incidentInformation);

I could directly set this value as the data value: (the Timeout has to be done this way and can not be set in the data object)

$http({   method: 'POST',   url: url,   data: incidentInformation,   timeout: 4000}).then(function (success) {   callback(success);}, function (error) {   errorCallback(error);});

With this changed code the backend now recieved the data correctly and my application is able to save the data.

Thanks Yoogeeks for suggesting the standard method. Strange that AngularJS $http."some method" works different than the standard method.