Creating a web server in Node.js with Express

26 November 2022


One of the main uses of Node.js is running web servers to accept and handle HTTP requests. The most popular library for doing this is Express. This post will teach you how to get started serving content with Express, whether you want to create an API or make a website.

Installing

To install Express run npm i express in your terminal. Now in your code you can import it:

const express = require('express');

Creating an express app

To create a new request handler with express you need to call it as a function:

const express = require('express');
const app = express();

Handling a request

Let's create your first endpoint, an endpoint is a path with a method. When your browser goes to a page, it sends a request to that path with a GET request. There are other HTTP methods such as POST, PATCH or DELETE. Let's create a simple GET request handler at / that responds with Hello world!:

app.get('/', (req, res) => {
    res.send('Hello world!');
})

Creating a server to listen on a port

Now you need to create an HTTP server for your Express app to handle requests from:

const http = require('http');

const PORT = 8000;
http.createServer(app).listen(PORT);

Now when you run your code, you should be able to visit localhost:8000 in your browser and see Hello world!.

Sending a file

Let's say you have an HTML file that you want to send the user when they visit your website, you can do that easily with the Response.sendFile method in Express. Your code might look something like this:

const http = require('http');
const express = require('express');

const app = express();
app.get('/', (req, res) => {
    res.sendFile(`index.html`, {root: __dirname});
})

const PORT = 8000;
http.createServer(app).listen(PORT);

Creating a JSON API

Express allows you to send JSON responds with the Response.json method. Let's make an API that returns the current date and time for demonstration purposes:

const http = require('http');
const express = require('express');

const app = express();
app.get('/date', (req, res) => {
    res.json({
        date: new Date()
    });
})

const PORT = 8000;
http.createServer(app).listen(PORT);

The endpoint of this API is /date.

Handling POST requests

POST requests allow the client to send files/data to the server in the body. We need a library to parse this incoming data. There is a handy library called body-parser so let's install that with npm i body-parser. This library provides middleware for requests, middleware is something that intercepts the request and does something with it before it reaches your handlers. Let's create an HTML form and then create code to serve the file and handle form responses.
First let's make our HTML file called index.html and put the following content in it:

<html>
    <head>
        <title>Form demo</title>
    </head>
    <body>
        <form method="post" action="/submit">
            <p>Please enter your name:</p>
            <input type="text" name="name" required>
            <p>Please enter your favourite food:</p>
            <input type="text" name="favouriteFood" required>
            <p>Please enter your age:</p>
            <input type="number" name="age" required>
            <input type="submit">
        </form>
    </body>
</html>

Now in your Node.js code you can put the following:

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));

// Serve the index.html file
app.get('/', (req, res) => {
    res.sendFile('index.html', { root: __dirname });
})

// Handle data submissions
app.post('/submit', (req, res) => {
    console.log('Received data:');
    console.log(req.body);

    // Send the user their favourite food that they just entered.
    res.send(`Your favourite food is ${req.body.favouriteFood}.`)
})

const PORT = 8000;
http.createServer(app).listen(PORT);

Now when you visit localhost:8000 in your browser, you should be presented with a form, you can fill it in and you should see the server reply with your favourite food.
Remember, when you receive data from a user you should always validate this data, the user can modify the data they send your server so you must make sure it matches up with what the form expects and is not missing any fields, has fields of the wrong type etc. to avoid errors.

Conclusion

In conclusion, Express allows you to easily handle requests. There are quite a lot of handy methods you can use to easily perform tasks, such as setting cookies in the user's browser with Response.cookie and redirecting the user with Response.redirect.

This has just been a brief introduction. We recommend you take a look at the Express docs to further your knowledge.


Explore more posts