简体   繁体   中英

In Node.js how do I communicate with client side JavaScript?

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 need (soft) real-time capabilities, I recommend using the Socket.io library . With socket, node can also push data to your client side scripts.

I think that NowJS will be a perfect fit for you. Example:

// On the Node.JS server

var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);

everyone.now.getServerInfo = function(callback){
  db.doQuery(callback);
}

// In the browser

<script>

now.getServerInfo(function(data){
  // data contains the query results
});

</script>

You can put variables and functions in a common namespace (ie the now object), from the client to the server and the other way around.

I think you need RPC . The node modules section also has a section covering RPC . I think you should have a look at DNode . Have a look at the DNode on the browser section .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM