Creating a Web Server in Node.js with Express
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.
npm version
in a console or terminal.
If you have them installed, go ahead and run the following in your console/terminal:npm i express
npm i body-parser
npm i path
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.
app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(bodyParser.text()); // Optional
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. });
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}/`); });
<!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>
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.