Start a web server with Node.JS and Express
Kavin Desi Valli
Posted on March 5, 2022
Node.JS and Express are two of the most used technologies in the web development world right now. It powers some big sites like Paypal, Wall Street Journal, Shutterstock and a lot more.
Getting started with Node.JS and Express is very easy.
Requirements
- You should have Node.JS installed for this tutorial. If not, visit https://nodejs.org/en/ and download the LTS Version. This will also install npm which is a widely used package manager for Node.JS.
- You're also expected to have a basic knowledge of Javascript and Node.JS.
Creating a project
First, let's start off with creating a Node.JS project/directory. You can run the following two commands on the the terminal. Alternatively, you can create a folder from your file manager and open it in VS Code or any other code editor of your choice.
mkdir node-express-tutorial
cd node-express-tutorial
code . # for Visual Studio Code users
Configuring the folder to use npm
Run the following in the terminal.
npm init
You will be prompted with a few questions. You can press enter through most of them.
Alternatively, you can run
npm init -y
if you want to skip through all the questions with the default value.
Starting with the coding part
So, start with creating a file named index.js
. You can name it anything, just make sure you end it with .js
.
Conventionally, the file is named
index.js
,server.js
orapp.js
.
Installing express
Like most NodeJS packages, you can install express using npm. Run:
npm install express
This will add express as a dependency in your package.json
and also install it in your node_modules
folder.
Using express
In your index.js
file, write the following:
const express = require("express")
If you've used Node.JS before, this should look familiar. This line basically imports the express package. Now, to use express, you need to instantiate the imported function. So:
const express = require("express")
const app = express() // add this line
Now, you can use the app variable to start the server like so:
app.listen(3000, () => {
console.log(`π Server started on port 3000`)
}
You've basically already created a web server. You can run the app by running
node index.js
If you get something like in the above gif, you're good to go to the next step!
Routes
So now, we've started an express server but it doesn't know what it has to do when we're visiting the /
route. Hence we get the error:
For this, add the following line of code before calling the app.listen
function:
app.get('/', (req, res) => {
return res.send("Hello, World")
})
Let's go through this code:
- We call the
app.get
function. This takes in two parameters:- A route: The route on which you want to run this function. In this case we're using the
/
route. - A callback function: The second parameter is a callback function with the
request
andresponse
parameters which express provides us with. Theres
(response) gives us a send function with which we can send back a text response to the browser.
- A route: The route on which you want to run this function. In this case we're using the
Now, we need to restart the NodeJS server running. Go to the terminal where you had run node index.js
and then hit Control-C
. And then restart by typing node index.js
again like so:
BONUS: Restarting the node server repeatedly becomes very annoying. To deal with this, there's a package called
nodemon
which you can install and setup. For detailed instructions visit: https://livecode247.com/how-to-add-auto-reload-to-your-node-js-app
Now, refresh the page on the browser and you should see this:
For the final step, you can refactor the port number like this
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`π Server started on port ${port}`);
});
process.env.PORT
returns the PORT environment variable which is set in many hosting providers so it is a good practice to use that instead of hardcoding a port. We're saying that if it doesn't exist, use port 3000.
Final Code
Your final code in index.js
should look like this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
return res.send("Hello, World");
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`π Server started on port ${port}`);
});
That's it for this tutorial! Now express has a lot more stuff to offer you. Just yesterday, MDN released it's new website and I found a very good in-depth tutorial on express. Do check it out here.
Posted on March 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.