Introduction
In this blog article, we’ll learn how to set up express and run an HTTP server instance using the express library.
Expressjs is a non-opinionated library for setting up an HTTP server for a REST API or web backend. Express never puts restrictions on how to set up your project.
Express is very lean, with no third-party libraries preinstalled. This makes Express powerful because express is easily extensible using middlewares.
Middlewares are functions that have access to the request
and response
objects. Middlewares intercept requests to your application and can check, validate, modify or read values from the request
and response
objects.
With that said, let’s set up a simple Expressjs application.
1. create a new project
To create a new project, run the following command to create a new directory and initialize a project. You may create the directory manually by going inside the directory, creating a new folder, giving the folder a name, then using Powershell run npm init -y
to initialize the project.
mkdir express-intro
cd express-intro
## initialize a Nodejs project
npm init -y
This creates an empty Nodejs project with a package.json
file that will hold project metadata and scripts
2. Install express
Install express
dependency from npm
npm i express
3. Create app.js
Create a file named app.js
, the name does not have to be app.js
, you can choose any meaningful file name.
- Import the
express
dependency:
const express = require('express')
- Initialize your application
const app = express()
- Declare a port, which the http server will listen for requests on
const PORT = process.env.PORT || 3000
Ideally, we’d want to read the value of PORT off process.env.PORT
if not available, use 3000
. This is good practice so that we don’t run into issues in production
4. create a route
A route maps to a resource on the HTTP server. on a seperate line:
app.get('/hello-world' , (req, res) => {
res.send('hello word!')
})
// run the http server on PORT 3000
app.listen(PORT, () => console.log(`app runinng at port ${PORT}`))
Download project code here: intro-to-express
This route will map to: http://127.0.0.1:3000/hello-world
Visiting this route on the browser:
Explanation
When we visit the /hello-world
route, we initiate a GET request to our http server. When the request
reaches the server the get()
method is called on our app instance, passing in the /hello-world
route name, and a callback function that has access to request
and response
objects.
Inside the callback, nothing special happens, we send back a response
to complete the request-response cycle.
This is a a sequel to tutorial serries on the Expressjs framwork. We shall cover the following areas:
- Setting up express
- Routing
- Middlewares
- Security practices
Summary
Express supports more http verbs such as:
- POST
- PATCH
- DELETE
Found this article helpful? you may preorder Modern JavaScript Primer to improve and help better understanding of Modern JavaScript.
Merry Christmas 🎄🎄🎄