Question

I am still a beginner in Node.js and I am trying to explore as much as I can.

I know that Express.js is a framework used by many people for creating websites in Node.js.

But without using Express.js, I know that it is it possible to read .html files using 'fs.readFile', and then "display" this .html file in the browser.

Is there a way to get user input (say a button click, or fill in a box) from this web page into Node.js? So far, I have not found any examples of this.

Was it helpful?

Solution

Yes, this is possible. Study how the connect bodyParser's urlencoded function works.

When a request comes in from the browser, node is going to represent this as a readable data stream. For web forms, the pattern will be:

  1. Use the request's data and end events to buffer the chunks of data from the stream into a single string.
  2. Parse that string appropriately given its data format. In the case of a web form, this will normally urlencoded (application/x-www-form-urlencoded) MIME type

.

  var qs = require('qs'); //https://github.com/visionmedia/node-querystring
  function handle(req, res) {
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){
      //assemble the request from distinct chunks into a single string
      buf += chunk
    });
    req.on('end', function(){
      //OK, you have a usable string request body, parse it and handle it
      try {
        var formData = qs.parse(buf);
        //Yay, it parsed. Now you have your form data
        //depending on your form's html, you might have formData.email, for example
      } catch (err){
        //oops, respond with an error          
      }
    });
  }

OTHER TIPS

Tutorial

Long story short:

http.createServer(function (req, res) {
    var data = '';
    req.on('data', function(chunk) {
        console.log("Received body data:");
        console.log(chunk);
        data += chunk.toString();
    });

    req.on('end', function() {
        console.log('Received Data: ', data);
        res.end();
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top