Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js user input from a website (not using Express.js)

Node.js user input from a website (not using Express.js)

Problem

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.

Problem courtesy of: FranXh

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          
      }
    });
  }
Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js user input from a website (not using Express.js)

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×