Node.js | Multi-page Routing and Form POST Submission

This article explains how to route multiple pages in Node.js and how to receive values submitted from an HTML form with POST.

Routing Multiple Pages

When a Node.js application serves several pages, the request URL is parsed and mapped to the template that should be displayed. The common layout is written in template.ejs, and each page body is separated into files such as content1.ejs and content2.ejs.

The basic flow is to prepare a route table, parse the request URL with url.parse, and choose the template from that table. If no matching route is found, return a 404 response.

var routes = {
  "/": "content1.ejs",
  "/content2": "content2.ejs"
};

var url_parts = url.parse(request.url);
var target = routes[url_parts.pathname];

After the page body is loaded with fs.readFile, it is rendered through EJS and inserted into the common template. This lets several pages share the same page frame while keeping their content files independent.

Sending a Form with POST

To send form values, create a form in content1.ejs and set method="post" and action to the route that receives the data.

<form method="post" action="/content3">
  <input type="text" name="idname">
  <input type="password" name="pass">
  <input type="submit">
</form>

The destination page can be prepared as another template, for example content3.ejs, and display the received values.

<p>ID: <%= idname %></p>
<p>PASS: <%= pass %></p>

In Node.js, POST data is received in chunks. Listen for the data event, collect the body text, and parse it with querystring.parse when the end event fires.

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

request.on("end", function() {
  var data = qs.parse(body);
  render(data);
});

GET access and POST submission should be handled separately. GET simply displays the form, while POST reads the request body and renders the result page with the submitted values. This routing pattern is the basis for building simple multi-page Node.js applications without Express.