Creating a Web Server in Node.js with Express



Local Web Server Tutorial












Table of Contents



1. Introduction
2. Code
3. Conclusion

Table of Contents



1. Introduction
2. Code
3. Conclusion



The Guide



Setting up a web server in Node.JS can be confusing at first, but it gets pretty simple. In this example, we will be using Node.js and Express. You can use other web frameworks, but I find that Express works well. If you would like a tutorial that goes a little more in-depth into possible applications of Express, check out this tutorial on Discord OAUTH2 with Node.js and Express.

The Code



To start off, let's go through our dependencies for this project. Before starting, be sure you have Node.js and npm installed. You can check if npm is installed by running npm version in a console or terminal. If you have them installed, go ahead and run the following in your console/terminal:
Those should be sufficient for now. Let's go ahead and create a file called index.js for our server-side code. Let's also write our first lines in that file.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = 7000;
const app = express();
if (isNaN(port)) process.exit(1); // Exits the program if the port is invalid.
    
The code above defines four variables: express, bodyParser, path, app, and port. The express, bodyParser, and path variables are modules that we will use later. Our port variable is for whichever port we would like our program to host on. The app variable defines a new express app. The server will then check if the port variable is invalid. If it is, the program will stop execution. Let's write our next chunk of code. Here, we will configure our app.
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(bodyParser.text()); // Optional
                
Those three lines of code allow our server to interpret incoming requests. Now, it's time to get to the fun part. Listening for incoming requests. To do so, we will use app.get(). This method will handle GET requests to the specified address.
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html')); // Send the index.html file. Path is used to more reliably get files from their names and the directory.
});
                
The code above will listen for any GET requests to http://localhost:(port)/ and if it receives any, it will send the index.html file, which we still have yet to create. This is most of the backend code! Let's quickly go through what the app.get() method is. When the app receives a GET request to the specified address (first parameter), the function (second parameter) will execute. There are also other methods provided by Express for other types of requests, such as POST. A POST request handler can allow you to host an API with express. An example of app.post() is included in this tutorial on Discord OAuth2. We're almost done. If you run the program now, you won't see anything when you go to the localhost link. That's because the app is not listening (and the index.html file has not been created yet). To make our app listen for requests, add in this snippet of code.
app.listen(port, () => {
    console.log(`App listening! Address: http://localhost:${port}/`);
});
                
This code will tell the app to start listening on the specified port variable and will log the link in the console when it is up.
Alright. We have the index.js file set up. Let's create our index.html file. I am just going to create an index.html file that prints Hello World! in an h1 tag, for the sake of this demo.
<!DOCTYPE HTML>
<html>

<head>
<title>Express.js Web Server Example</title>
<meta charset="utf-8" />

<style>
    #main_text {
        text-align: center;
    }
</style>
</head>

<body>
<h1 id='main_text'>Hello World!</h1>
</body>

</html>
                
This code is just a basic and simple HTML file that will print "Hello World!" on the page. But we've completeted the code!

Conclusion



To run the program, navigate to the directory in your terminal/console, type in node index.js, then navigate to http://localhost:7000/ (or whichever port you chose to use). You can add more files and paths. This just covers setting up a simple web server with Node.js.
Happy programming!

Related Articles