1

What is the best way to send data from Angular js to node js restful service which uses express. My Angular js code is as follows:-

var myController = function("myController", $scope) {
$http.get("/someUrl", {key1:"value1", key2: "value2"}).then(function(response) { alert(response.data);});

On the Node js end :-

app.get("/someUrl", function(req, res) {console.log(req.body);});

I can see that console.log is displaying {}. Is there a way to send the json input for get as well.

By the way for Nodejs I used express module, I have used body-parser and set all the other things needed.

I am using Angularjs 1.4 and Nodejs express 4.

1
  • My friend asked me the Question for a use case where he want's to hit a restful service to authenticate the user's credentials. I am not sure if using params like $http({ method: 'GET', url: '/url', params: params }) is a good option or not. Commented Feb 5, 2016 at 21:11

2 Answers 2

1

You can use both $resource and $http. With $resource you can leverage the consistency of REST APIs, since it will use the familiar structure to build the endpoints, so there's a little magic going on.

Using $resource:

var Dog = $resource('/dogs/:dogId', { dogId :'@id' });

var fido = new Dog({ name: "Fido" });
fido.$save();

// POST to /dogs/ with data: { name: "Fido" }

With $http you're more explicit. You can send data like this:

$http({
    method: "get",
    url: "...",
    params: {
        key1: "value1",
        key2: "value2"
    }
});

And like this:

$http({
    method: "post",
    url: "...",
    data: {
        key1: "value1",
        key2: "value2"
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

in your node server now its

app.get("/someUrl", function(req, res) {console.log(req.body);});

try this

app.get("/someUrl", function(req, res) {console.log(req.body.key1);});

1 Comment

The answer can become more valuable if you are adding some explanation and links to documentation, so the original poster and other users can actually learn from it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.