Building an Express App
January 24th 2021 74

In this chapter, we will learn how to start developing and using the Express Framework
. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.
node --version
npm --version
You should get an output similar to the following.
v5.0.0
3.5.2
Now that we have Node and npm setup lets start,
Whenever we create a project using npm, we need to provide a package.json
file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.
Step 1 − Start your terminal/cmd
, create a new folder named hello-world
and cd (create directory) into it −
Step 2 − Now to create the package.json
file using npm, use the following code.
npm init -y
Step 3 − Now we have our package.json
file set up, we will further install Express
. To install Express
and add it to our package.json file, use the following command −
npm install --save express
Tip − The --save
flag can be replaced by the -S
flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install
and it will find the dependencies
in this file and install them for us.
This is all we need to start development
using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon
. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −
npm install -g nodemon
We have set up the development
, now it is time to start developing our first app
using Express
. Create a new file called app.js
and type the following in it.
// import module
var express = require('express');
// initialize express app
var app = express();
// accept request and send a response
app.get('/', function(req, res){
res.send("Hello world from server!");
});
// listen on PORT 3000 for incoming HTTP request
app.listen(3000);
Save
the file, go to your terminal and type the following.
nodemon app.js
This will start the server
. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following demo.