Creating Simple Express Server App
Express or Express.js is a web framework that runs on Node.js. It provides a set of tools that you need when creating a web server.
Installing Express Locally
You should already have Node.js already installed on your computer.
Create a new folder with the name of your choice. This folder will hold your project files. In my case, the folder is called express-server
.
Open the terminal and navigate to your folder.
/express-server$
Inside your run the command npm init
. Press enter for all entries.
This will create a package.json file in your folder with the following information.
{
"name": "express-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Then, run either npm install express
or yarn add express
.
Once express is installed, you should see it in your package.json file.
{
"name": "express-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1"
}
}
With express installed, you can proceed to writing your first Express app.
Write Hello World Express App
Open your index.js
file and add the following Hello world code.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Your express server is ready to receive requests'))
That’s all the code you will need to run your first Express app.
Running Simple Express App
To run you Express app, run the node index.js
on your terminal.
/express-server$ node index.js
In the terminal, you will see:
Now open a browser of your choice. For the address, enter localhost:3000
or http://127.0.0.1:3000
. You should see:
Hello World Express App Code Explanation
We first import the Express package that we previously installed.
const express = require('express')
Then, we add the package into our project.
const app = express()
Next, we need to tell the server what to do with the different requests it will receive. In our case we tell the server to respond with hello world!
when someone visits the home page /
.
app.get('/', (req, res) => res.send('Hello World!'))
Finally, to starts the server and ensure it is ready to accept requests use app.listen
. We added a log statement so that we can know when the app is ready.
app.listen(port, () => console.log('Your express server is ready to receive requests'))