How to make a REST request in my case? - angularjs

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.

Related

jmeter returns undefined as output

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

PUT request not working in Node.js

I am trying to update an existing document in mongodb with node.js. But it does not seem to work. It do not even display the request call in the console. Please suggest what mistake I am doing or how I can I do the update operation in node.js with mongodb. Here is the code:
Node.js Code:
app.put('/addIssueId', function(req, res) {
console.log("Adding issue id")
console.log(req.body.issueKey)
impactMapFeature.update( {productName:req.params.productName, actor:req.body.actor, activity:req.body.activity,feature:req.body.feature},{issueKey:req.body.issueKey}, function ( err, data ) {
console.log("Updating" + data)
});
});
Angular Controller code:
var data = {
productName: $scope.productName,
actor: actor,
activity: impact,
feature : $('#feature').val(),
issueKey : data.key
};
$http.put('/addIssueId', data)
.success(function(data){
}).error(function(data){
console.log('Error in adding issueId' + data)
});
}
As chridam said, you are using req.params which is a route parameter. Either use the following route : /addIssueId/:productName or pass your variable with a query parameter : /addIssueId?productName=productName and {productName = req.query.productName, ... }, or pass your variable as you are doing it in the body (then you just need to change req.params.productName to req.body.productName

How to send multiple parameters in AngularJS $http.post to Web API controller action method

How to send multiple parameters in an angularjs $http.post to web api controller action method.
Below is my code.
AngularJS code
var complexObj = { prop1: "value", prop2: "value" };
var id = 100;
var data = { id: id, complexObj: complexObj };
$http({
method: 'POST',
url: 'http://localhost/api/WebApiController/MethodName',
data: data
}).success(function (data, status) {
//do something...
});
$http.post('http://localhost/api/WebApiController/MethodName', data)
.success(function (data, status) {
//do something...
});
Web API controller
[RoutePrefix("api/WebApiController")]
public class WebApiController: ApiController
{
[Route("MethodName")]
public ReturnValue WebApiAction(string id,ComplexObj complexObj)
{
// process request and return data...
}
}
I am getting below response message in fiddler.
{ "message": "No HTTP resource was found that matches the request
URI 'http://localhost/api/WebApiController/MethodName'.",
"messageDetail": "No action was found on the controller
'WebApiController' that matches the request." }
When I send the complexObj alone, its hitting the web api,but all properties are null or set to default values.
What am I doing wrong? How can I send two or more parameters(both complex objects and string/int) in $http.post? Any help is much appreciated.
Web API doesn't support multiple post parameters in this way.
Your best bet is to roll up Id into ComplexObj and post it as a single parameter.
complexObj.id = id;
var data = complexObj;
Update your signature to take just a single object.
[Route("MethodName")]
public ReturnValue WebApiAction(ComplexObj complexObj)
{
// process request and return data...
}
If you absolutely want to be able to post data like this, consider Rick Strahl's post on creating a custom parameter binder.

Turn request success into error based on response data

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

Angularjs issue in relacing Ajax request with promises in service

For my Angularjs application in services I have used Ajax call to get the data and is as follows :
var originalRequest = $.ajax({
async : false,
url : "/dash/dashboard2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : formattedFromDate,
toDate : formattedToDate
},
dataType : "json",
success : function(originalRequest) {
var res = originalRequest;
data = res.ResultSet.Response;
}
});
Then I just return (data) from my service and in my controller I am able to get data without any problem. But I realized it is a bad practice and trying to use promises. So I have replaced it as follows:
var originalRequest = $http({
url: "/dash/dashboard2ajax.do",
method: "POST",
data: {action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : formattedFromDate,
toDate : formattedToDate}
}).success(function(data, status, headers, config) {
return (data);
}).error(function(data, status, headers, config) {
return(status);
});
But it is not working. None of the parameters are getting even passed to my action class. Is there any mistake in my syntax?
In my action class, I am accessing the parameters as
String action = request.getParameter("action");
But it is coming as null.
You're trying to replace jQuery.ajax with AngularJS $http, which has completely different contract. The thing you're calling originalRequest is not in fact any kind of "request object". It's just a Promise (extended with success and error methods). If you want to access the request data outside your success/error handlers, you need to save and pass it separately yourself:
var data = {
// ...
};
var request = $http({
data: data,
// ...
});
return {
request: request,
data: data
};
If you need to access it inside the handlers, just get it from the config argument:
$http(...).success(function (data, status, headers, config) {
var action = config.data.action;
// ...
});

Resources