Prateek Sharma Prateek Sharma - 2 months ago 7
Javascript Question

req.param gives undefined on server side : nodejs

I am using nodejs and angularjs.

1) I sent get request to nodejs server with required data in parameters in my client side js.


********* itinerary.js ************

$http({
method : "GET",
url : '/createItinerary',
data : {
"source" : $scope.sourceDestination.source,
"destination" : $scope.sourceDestination.destination
}
})


2) I the node js file, when I am using req.params("source") or req.params("destination"), I am getting undefined in them.


********* createIitinerary.js ************

exports.check = function(req,res){
// These two variables come from the form on
var source = req.param("source");
var dest = req.param("destination");

console.log("source:"+source);
console.log("dest:"+dest);

var json_responses;

if(source == dest){
json_responses = {"statusCode" : 401};
res.send(json_responses)
}
else{
json_responses = {"statusCode" : 200};
res.send(json_responses);
}};


Question: When I use Post, the data is correctly received in nodejs, but not with Get. Why is this ? How can I send data to nodejs using Get request.

Thanks.

Answer

For $http.get() you set params not data

Try:

 $http({
        method : "GET",
        url : '/createItinerary',
        params: {
            "source" : $scope.sourceDestination.source,
            "destination" : $scope.sourceDestination.destination
        }
    })

it should be easy to inspect the url used in browser dev tools network and make sure it looks right

Comments