Node.js has the core module http for handling HTTP requests. In this post we will see how to serve static files using the aforementioned form.
Create a server
To be able to handle HTTP requests we must first create a server through the method <code>createServer()</code>, which accepts a callback function as a parameter.
This function, in turn, accepts two parameters, <code>req</code>( request ) and <code>res</code>( response ), which are nothing more than two objects containing methods and properties for handling requests and responses.
The method <code>listen</code> actually places the instance of our server listening on a specific port (in this case 3000).
'use strict'; const http = require('http'); const server = http.createServer((req, res) =&gt; { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ method: req.method, url: req.url, headers: req.headers }, null, 2)); }); server.listen(3000);
The method <code>writeHead()</code> serves to send HTTP headers to the client, while the method <code>end()</code> sends data to the client and closes the request.
In the example, we can see some important properties of the request object, which is the HTTP method used ( <code>GET</code>, <code>POST</code>, <code>PUT</code>, etc.), The requested URL, and the headers sent by the client to the server.
Our base server responds to any URL passed to the loopback address on port 3000, such as http: // localhost: 3000 / or http: // localhost: 3000 / test.
Query string
By default the Node module does not automatically handle string queries as object properties <code>request</code>.
In fact, string queries are part of the URL passed to the server and must be extracted using the <code>parse()</code> core module method <code>querystring</code>, which returns a literal object in which the parameter / value pairs become properties and values of that object.
'use strict'; const http = require('http'); const qs = require('querystring'); const normalizeUrl = (url) =&gt; { if(url.indexOf('?') !== -1) { return url.replace( /\/\?/g, '' ); } return url; }; const server = http.createServer((req, res) =&gt; { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify( { url: req.url, query: qs.parse(normalizeUrl(req.url), '&amp;', '=') } , null, 2)); }); server.listen(3000);
In this case we removed the string from the URL <code>/?</code> (if present), before passing the URL to the method <code>parse()</code>, which as seen also accepts the parameters separator of the query string as parameters and the separator between the parameter name and the corresponding value.
POST requests
Requests <code>POST</code> are treated as data (stream), so we must use stream events to assemble the request body as a string and then derive the query string as we saw above.
'use strict'; const http = require('http'); const qs = require('querystring'); const post = (request) =&gt; { return new Promise((resolve, reject) =&gt; { if(request.headers['content-type'] === 'application/x-www-form-urlencoded') { let body = ''; request.on('data', chunk =&gt; { body += chunk.toString(); }); request.on('end', () =&gt; { resolve(qs.parse(body)); }); } else { reject(null); } }); }; const server = http.createServer((req, res) =&gt; { post(req).then(body =&gt; { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body, null, 2)); }).catch(err =&gt; { res.writeHead(403, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({msg: 'Invalid request'}, null, 2)); }); }); server.listen(3000);
In this case, we verify that the request is actually sent by an HTML form and then incrementally assemble the body of the request from which we extract the query string using the method seen above, with the only difference that in this case we do not have to dealing with a URL.
Serve HTML pages
To serve HTML pages we must interact with the file system and read the contents of the files as a string and then send the content to the browser with the appropriate MIME type.
use strict'; const http = require('http'); const fs = require('fs'); const get = (request, response) =&gt; { if(request.method === 'GET' ) { if(request.url === '/') { let home = fs.readFileSync('./templates/home.html').toString(); response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(home); } else { let notFound = fs.readFileSync('./templates/404.html').toString(); response.writeHead(404, { 'Content-Type': 'text/html' }); response.end(notFound); } } else { response.writeHead(405, { 'Content-Type': 'text/plain' }); response.end('Method not allowed'); } }; const server = http.createServer((req, res) =&gt; { get(req, res); }); server.listen(3000);
The home page will serve the requested file, while the other URLs will serve an HTTP 404 error page. If the type of request is not GET, we will send an HTTP 405 status indicating that the method used is not allowed.