0

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.

2
  • Only with the core modules? Commented Apr 4, 2013 at 7:46
  • yes, only with the core modules Commented Apr 4, 2013 at 13:21

2 Answers 2

2

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          
      }
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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();
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.