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.
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"
}
});
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);});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.