How to call a server side function from client side (e.g. html button onclick) in Node.js?

Here’s an example using Express and a HTML form.

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);

app.use(express.bodyParser());
app.post("https://stackoverflow.com/", function(req, res) {
  console.log(req.body);
  res.send(200);
});

server.listen(process.env.PORT, process.env.IP);

The code above will start an instance of Express, which is a web application framework for Node. The bodyParser() module is used for parsing the request body, so you can read post data. It will then listen for POST requests on the route /.

<form method="post" action="https://stackoverflow.com/">
  <input type="test" name="field1">
  <input type="test" name="field2">
  <input type="submit">
</form>

And if you submit that form, in req.body for the route /, you will get the result:

{ field1: 'form contents', field2: 'second field contents' }

To run a function, just put it inside the POST handler like this:

var foo = function() {
  // do something
};

app.post("https://stackoverflow.com/", function(req, res) {
  console.log(req.body);
  res.send(200);

  // sending a response does not pause the function
  foo();
});

If you don’t want to use Express then you can use the native HTTP module, but you’d have to parse the HTTP request body yourself.

var http = require('http');
http.createServer(function(request, response) {
  if (request.method === 'POST') {
    var data="";

    request.on('data', function(chunk) {
      data += chunk;
    });

    request.on('end', function() {
      // parse the data
      foo();
    });
  }
}).listen(80);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)