For example suppose client side I have a JavaScript function
function getLocation() {
var latitude = ...;
var longitude = ...;
}
The coordinates are retrieved using a function call to Google or similar. How can I transmit this information to my Node.js server?
The easiest way? Set up Express and have your client side code communicate via Ajax (for example, using jQuery).
(function() {
var app, express;
express = require("express");
app = express.createServer();
app.configure(function() {
app.use(express.bodyParser());
return app.use(app.router);
});
app.configure("development", function() {
return app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.post("/locations", function(request, response) {
var latitude, longitude;
latitude = request.body.latitude;
longitude = request.body.longitude;
return response.json({}, 200);
});
app.listen(80);
}).call(this);
On the client side, you might call it like this:
var latitude = 0
, longitude = 0; // Set from form
$.post({
url: "http://localhost/locations",
data: {latitude: latitude, longitude: longitude},
success: function (data) {
console.log("Success");
},
dataType: "json"
});
Note this code is simply an example; you'll have to work out the error handling, etc.
Hope that helps.
By making an HTTP request, just like you would with any other server side program in a web application.
You could do this with the XMLHttpRequest object, or by generating a <form>
and then submitting it, or a variety of other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With