I send over data from my Angular JS to my node API in following manner:
Inside Angular:
$http({
method : "POST",
url : '/add',
data : {
"a" : $scope.a,
"b" : $scope.b
}
}).success(function(data) {
$scope.result = data.result;
}).error(function(error) {
$scope.result = 'Invalid data...';
});
Inside my nodejs API definition:
exports.execute = function(req, res){
var a = req.body.a;
var b = req.body.b;
var result;
result = Number(a) + Number(b);
var json_responses;
console.log('from api add');
console.log((a));
console.log(b);
console.log(result.toString());
json_responses = {"result" : result.toString()};
res.send(json_responses);
};
The API and angular work just fine when I enter values from browser, the actual values are printed on the console.
But, when I try to post data using POSTMAN or use data for JMETER load balance testing, the console prints data as "undefined".
The ways I tried defining the data are:
data={
a : 100,
b : 100
}
data={
"a" : "100",
"b" : "100"
}
data={
"a" : 100,
"b" : 100
}
Anything that I am missing??
You need to set header Content-Type and value must be application/json to accept in req.body while Content-Type sent by AnguarJS is application/json by default
Related
AngularJS is not creating JSON as desired. With code (below) , it generates array (serialized steam ) but not form . ie
I am getting
{
data : 'value',
date : 'value'
}
But wanted - JSON ie
{
"data" : "value",
"date" : "value"
}
The code for Angular to POST json is ( snippet )
<script>
// Defining angularjs application.
var postApp = angular.module('postApp', []);
// Controller function and passing $http service and $scope var.
postApp.controller('postController', function($scope, $http) {
// create a blank object to handle form data.
$scope.user = {};
// calling our submit function.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'user.php',
data :JSON.stringify($scope.user),
headers : {'Content-Type': 'application/json'}
})
.success(function(data) {
if (data.errors) {
// Showing some error which has to come from server
} else {
$scope.message = data.message; //make the json
}
});
};
});
</script>
What should i do to get JSON and not Array ?
If you want your data in JSON format you should use JSON.parse();
$http({
method : 'POST',
url : 'user.php',
data :JSON.parse($scope.user),
headers : {'Content-Type': 'application/json'}
})
have you tried angular.toJson method?
Solved .
by using nothing ie.
json: $scope.user it works ...
How can i pass query params as arguments in angularjs http services.
My controller code is:
FetchHeadCategoryService.get({
'officeJndi': officeJndi
}, function (response) {
$scope.headCategories = response;
});
Service.js
module.factory('FetchHeadCategoryService', [
'$resource',
'SYSTEM',
function($resource, SYSTEM) {
return $resource(SYSTEM.ENV.API_END_POINT
+ 'v1/utility/headCategories/:officeJndi ', {
officeJndi : '#officeJndi'
}, {
get : {
method : 'GET',
isArray : true
}
});
} ]);
HeadCategory.java
public Response fetchDocMgmtHeadCategory(#PathParam(value = "officeJndi") final String officeJndi, #QueryParam(value = "limitFrom") final int limitFrom,#QueryParam(value = "noOfRows") final int noOfRows){
..
..
..
}
I can obtain the result without passing the query params by managing them in the code.
But I want to send the value of query params "limitFrom" and "NoOfRows" to the service ,so that i acn fetch the data accordingly.Can somebody HELP.
Try to use params option to send additional data
get : {
method : 'GET',
isArray : true,
params: /* your data {} */
}
I am reading a RESTFUL API doc and one of the PUT methods requires request body to be sent.
The doc mentions
PUT /api/v1.2/product/{id}
with request body like
{
"name" : "Toy",
"description" : "Kids toy",
"price" : 25
}
my current request codes.
$http.put('/api/v1.2/product/' + ID);
I am trying to use Angular http request to make the call but not sure how to make the request with the request body. Can someone help me about it? Thanks a lot!
The data goes in the second parameter to put. For example:
var data = {
"name" : "Toy",
"description" : "Kids toy",
"price" : 25
};
$http.put('/api/v1.2/product/' + ID, data)
.success(function(response, status, headers, config){
//do something with response here.
})
.error(function(response, status, headers, config){
//handle error here.
$scope.error_message = response.error_message;
});
For more info, see here
The angular defines some syntax, you have to main that other wise you won't do anything. You can try is
JS CODE
var data = {
"name" : "Toy",
"description" : "Kids toy",
"price" : 25
};
$scope.save = function () {
$http.put('/api/v1.2/product/' + ID, data).success(function (data) {
}).error(function (data) {
$scope.error = "An Error has occured while Saving customer! " + data;
$scope.loading = false;
});
};
API CODE
public HttpResponseMessage Put(int ID, Product product)
{
}
I have written a article into code project here. From here you can get full concept of $http get , put, delete.
$resource possibly provides a nicer api (though still uses $http under the hood)
Given your data:
var data = {
"name" : "Toy",
"description" : "Kids toy",
"price" : 25
};
Setup your resource
var Product = $resource('/api/v1.2/product/:id', { 'put': { method:'PUT' } });
Then to make a request with it, you just need to:
Product.put({ id: ID }, data);
If you want to handle a response or errors, just pass the callbacks in too:
Product.put({ id: ID }, data, function(data){ }, function(error){ });
Check out the documentation: https://docs.angularjs.org/api/ngResource
It can do some pretty cool stuff with promises (Not that $http can't, $resource is just a little nicer IMHO)
It provides GET, POST and DELETE methods by default. PUT is a special case so thats why we needed to specify it above.
I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.
In services :
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
In Controller,
DashboardsDataService.getNetSpendOverTimeData()
.then(function(data) {
$scope.data = data;
});
The following is my original request to Java action class:
var originalRequest = $.ajax({
async : false,
url : "/dash2/dashd2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : fromDate,
toDate : toDate,
modes : selectedModes,
services : selectedServices,
dateType : selectedDateType,
lanesList : selectedLaneList
},
dataType : "json"
});
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:
return $q.when(originalRequest).then(function (res) {
if (res.ResultSet.error) {
return $q.reject(res.ResultSet.error);
} else {
return res.ResultSet.Response;
}
});
Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:
doSomethingAsynchronous().then(function (data) {
$scope.data = data;
}, function (error) {
$scope.data = [];
alert(error);
});
i'm working on a project like this:
(HTML Forms(AJAX)+ twitter bootstrap)(solo HTML, no JSP,etc..)->Servlets(on Google App Engine-JAVA)->Persistence(Google Cloud SQL).
I'm quite new to jQuery ajax calls, but i understand the process, as i'm used to write the old XHR code.
Below is the function in JS, that does not write to console the expected result..so far most of the times form data is persisted.
My Servlet if fine, and outputs a valid JSON.(calling the URL on a browser always works as expected.)
My answer is why jQuery ajax callbacks(done,fail,always) aren't working properly? They do write to console/display alert().
THANKS, for your time!
$(document).ready(function() {
var myEmail = "";
var myGender = "";
$('#saveButton').click(function() {
$('#myform').submit();
//alert('Handler for .submit() called.');
myEmail = document.getElementById("inputEmail").value;
window.console.log('EMAIL---->' + myEmail);/*ok log!*/
//alert('EMAIL->' + myEmail);
var radioObj = document.forms['myForm'].elements['gender'];
myGender = getCheckedValue(radioObj);
window.console.log('GENDER---->' + myGender);/*ok log!*/
//alert('GENDER->' + myGender);
var jqXHR = $.ajax({
statusCode : {
404 : function() {
alert("404 ERROR - page not found");
}
},
url : "/newuser",
type : "GET",
timeout : 10000,
data : {
email : myEmail,
gender : myGender,
operation : '0'
},
done : function(data, textStatus, jqXHR) {
window.console.log('done -> RESPONSE---->' + data);/*this does not log!*/
alert(data);
},
fail : function(jqXHR, textStatus, errorThrown) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
},
always : function(data, textStatus, jqXHR) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
}
});
});
});
done, fail and always are not properties of the settings object passed to $.ajax, they are callbacks on the jqxhr object returned by the call to $.ajax. They should be configured like this instead:
var jqxhr = $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Check out the API documentation for further usage guidance.