7

I'm trying to make a simple form, with user name and last name, and when the user submit information, another page is displayed. I did a form in html, but I'm not sure about what to do next? Does anyone have a small, self-contained example of a form, using node js?

1
  • There are lots of examples on github. For example, look at this one. Commented Jul 20, 2013 at 13:10

1 Answer 1

13

This example does not quite complete your task. But it is a self contained node.js program that displays a form and a different page upon form receipt.

Copy it into a file and then run node filename.js and then go to http://localhost:3000 in a browser.

Take note of the asynchronous code structure. I define a handler function but don't execute it immediately. We instead pass the function to http.createServer and then call .listen(3000). Now when an HTTP request comes in, the http server will pass a req, res pair to the handler function. req is the request object (this will contain the form data; see this question for some hints on how to get that data out. (I suggest that you jump right in and build a small Express app. It's a really nice framework.)

//app.js
// Load the built in 'http' library
var http = require('http'); 
var util = require('util');

// Create a function to handle every HTTP request
function handler(req, res){
  if(req.method == "GET"){ 
    console.log('get');
    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200);
    res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
  } else if(req.method == 'POST'){
    console.log('post');
    // Here you could use a library to extract the form content
    // The Express.js web framework helpfully does just that
    // For simplicity's sake we will always respond with 'hello world' here
    // var hello = req.body.hello;
    var hello = 'world';
    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200);
    res.end("<html><body><h1>Hello "+hello+"!</h1></body></html>");
  } else {
    res.writeHead(200);
    res.end();
  };
};

// Create a server that invokes the `handler` function upon receiving a request
// And have that server start listening for HTTP requests
// The callback function is executed at some time in the future, when the server
// is done with its long-running task (setting up the network and port etc)
http.createServer(handler).listen(3000, function(err){
  if(err){
    console.log('Error starting http server');
  } else {
    console.log('Server listening on port 3000');
  };
});
Sign up to request clarification or add additional context in comments.

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.