Maria Jane Maria Jane - 3 months ago 7
Node.js Question

restful API using node not returning anything

In my server.js I do:-

app.post('/app/getSingleOrderDetail', function(req,res,next){
orderController.getSingleOrderDetail(req.body.order_id);
})


then in models

exports.getSingleOrderDetail = function(order_id, res, res) {
Orders.find({'_id':order_id}).exec(function(err,result){
console.log('result: '+result) //it's ok!!
res.json(result);
});
};


I'm expecting the result with this
$http
call in angularjs

$http({
url: '/app/getSingleOrderDetail',
method: "POST",
data: {'order_id' : id}
}).then(function(response){
console.log(response.data)
vm.sales_detail = response.data;
}).catch(function(response) {
alert('Error!');
console.log(response);
});


Everything is passed correctly but I just couldn't get the data back to client side in angularjs.

Answer

In getSingleOrderDetail you're expecting the arguments (order_id, res, res), When you're invoking the function though, you're only passing in a value to the first argument, order_id and nothing for res. Also, you've defined res twice which is going to cause an issue in your code when trying to access res.

You should fix up those issues like so

Route

app.post('/app/getSingleOrderDetail', orderController.getSingleOrderDetail);

Model

exports.getSingleOrderDetail = function(req, res) {
  let order_id = req.body.order_id;

  Orders.find({'_id': order_id}).exec(function(err,result) {
    if (err) return res.status(500).send(err);

    console.log('result: ' + result); //it's ok!!
    return res.status(200).json(result);
  });
};

Just a side note, from the looks of your route name, this wouldn't be considered RESTful, it would be more of an RPC (Remote Procedure Call) style API.