NodeJs and Express: Get Started building web app
NodeJs and Express: Get Started building web app
ExpressJs is a popular NodeJS framework written in JavaScript. This article explains
- How to get Started with ExpressJS
- Build a sample App with ExpressJs framework
While this is an article about Getting started with Express and Node. But if you are interested in building Video Calling APPS refer to this article WebRTC and NodeJS
Installation
You need to install NodeJs first before installing express. You can learn more about installing node on the NodeJs website.
Once you have installed Node, follow the below steps to install ExpressJs. I am using Node 16.x.x in this tutorial.
First we need to create a directory, I am assuming you are on a Linux, Mac or Wsl on Windows
Create a directory
mkdir myapp
Once you have done this then
cd myapp
After this type npm init
to initialize a new project, You will have some options to go through like:
- package name
- version
- description
- entry point
- test command
- git repository
- Keywords
- author
- license Then it will give you a confirmation if this is ok. confirm yes
Now we will install ExpressJs. write the below command to install ExpressJs
npm install express --save
This will also save the ExpressJsas a dependency in the package.json
file. Now open the code editor of you choice. I am using VS code but you can use any code editor you prefer.
Create a file and name it index.js
, we will be writing code in this file. Paste the below code in the file
const express = require('express');
const app = express()
const port = 8080
app.listen(port, () => {
console.log('Sample APP listening on port 8080);
})
In the above code we have created a server and the server is listening for on port 8080 but we haven't created any routes.
We will need to create routes so that front end application can call and we can send data through those routes
Creating ExpressJs routes
Lets create a get route and we will send a "Hello World" when we get a request on it. Add the following code on the index js file
app.get('/', (req, res) => {
res.send('Hello World!')
})
We can test that this route is working by opening up a browser and going to localhost:8080 where you will see the response from our server that is "Hello World"
You can create even more routes with express like
- GET
- POST
- PUT
- DELETE
like this
A post request
app.post('/', (req, res) => {
// You can write the logic about what to do here
res.send('POST request recieved')
})
A PUT request
app.put('/candy', (req, res) => {
// you can write the logic to update here
res.send(' PUT request at /candy')
})
A Delete Request
app.delete('/store', (req, res) => {
// you can write the logic to delete the store here
res.send('DELETE request at /store,')
})
If you are wondering what are req
and res
.
What is a Request
req
is basically short for request
. It is the first argument that you need to write when defining a route in express. request
is the request that you send from your client to the server.
What is a Response
res
is short for response
.
res
basically the second argument that you need to write when you define an route in express. Response is the response that you send from your server to the client.
Serving Static Files in Express middle ware
Express has a built in middleware function to serve static files to users such as HTML files, CSS and Javascript files.
(We will learn more about what are middleware functions and what are their uses after this section).
express.static(root, [options])
the root
is the root directory that you need to specify for the server to send the files from. For example if you have a directory or folder named public
that you need to serve you can write the code like
app.use(express.static('public'))
Using middleware
With ExpressJs you can create middle ware functions that have access to all the routes
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Middle ware functions are used using theapp.use
nomenclature.
We can use third party or express middleware and we can also write our own custom middleware.
To use a middleware simple write app.use
and pass it a function.
The middleware function must end the request response cycle or pass it to the next middleware function using the next()
function so that the next middleware can execute the rest of the code and end the request response cycle other wise the request will be left hanging
In the example below we will logging in the time that is now and pass the request to the next()
middleware function for it to handle the rest of the code.
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
We can either end the request response cycle here and return the Time or we can call the next middleware function. We are choosing to call the next middleware function
Using middleware on specific routes
We can make it so that requests on specific routes are handled by the middleware. Like in the example below
app.use('/user/admin', (req, res, next) => {
console.log('Request Type:', req.method)
next();
})
By typing the /user/admin
as the first argument to the app.use()
the middleware function will only run for requests sent to /user/admin
route.
Chaining Multiple Middleware requests
In the example above we called the next()
function to handle the rest of the code. We also used a specific mount path so that requests send to the mount path are handled by the middleware
Here is a example of a series of middleware paths that prints the requests info for any type of http requests basically chaining the middleware functions
app.use('/user/admin', (req, res, next) => {
//log the orignalURL
console.log('Request URL:', req.originalUrl)
//calls the next middleware here
next()
}, (req, res, next) => {
//logs the req.method here.
console.log('Request Type:', req.method)
next()
})
Using third party middleware
You can easily install third party middleware with ExpressJs. Simply install the middleware using npm
and use
it in your app.
like example: We will be installing the cookieParser middleware in this example
npm install cookieParser --save
Type --save to save it in your `package.json
file
then add it to your `index.js
file like so
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())
Using the express generator
Express generator is a tool that creates a application skeleton for you to quickly start working with,
You can run the application generator with the npx
command
npx express-generator
run the express -h for any help with the express generator
Summary
In this article we have learnt how to build an app with ExpressJs and NodeJS. Let me know what you think about it in the comment section below.
If there are any doubts or if you need any help I am here to answer your questions.
I request you to share this article as well if you find it useful