Build your First Express server in less than 5 Minutes
Learning Express.js can be a valuable experience in your web development journey
The first step is always initiating our package.json file which is like the ID card that stores information about a particular web-based project including the dependencies
On the Terminal, move to the current working directory and type the following (assuming you have node.js installed)
npm init
This command will prompt you to type your package name, version, description, entry point, test command, git repository, keywords, author & license.
For simplicity's sake Package name, entry point and author details will be enough
We can evaluate package.json before installing express
Let's install Express still in the same folder
npm install express
This command will add the express package to our dependency
Create a new index.js file since this is what we mentioned as our entry point in our package.json
In the index.js let's call express
const express = require('express')
const app = express()
app.listen(3000, function() {
console.log("Server is running on Port 3000")
})
In the first line, we are calling the express class in the same way as in PHP, Python, C
In the second line, we are storing our express method in a constant called "app". This is universal across Express.js apps as you will often see an "app" constant.
Finally, the "listen" method that comes with express is where we tell our port number to listen for our app. The default will always be 3000.
For the sake of our reference, we can include a callback function that will log the message to know if our server is running or not
Let's start our web server
Let's run our index.js with the 'node' prefix in the same way as we would run our Python program like python main.py
node index.js
We got our first express server up and running. But when you visit http://localhost:3000/ you will get an error as "Cannot GET /".
Since we have not created our HTML pages yet the GET request will send an error So let's fix this by adding a single line
app.get("/", (req,res) => res.send("Hello World"))
Just like the listen method, the get method comes with our express package and as the name suggests we are sending a GET request. The req and res stand for request and response cycle. We are sending our data using "send" method of our response cycle.
The "/" indicates our home directory or the index directory. For example
https://hashnode.com/
is same as
https://hashnode.com
Our Final version of index.js looks like this
const express = require('express')
const app = express()
app.get("/", (req,res) => res.send("Hello World"))
app.listen(3000, function() {
console.log("Server is running on Port 3000")
})
Let's navigate to http://localhost:3000/ on our browser. You will see the "Hello World" message we sent using the res. send method through our express server.
You just built your very own Express Server ๐