Introduction to Express JS

Express.Js is a popular node js framework which makes developing API’s a breeze.

Getting started

To start using express, you first need to install node.js, you can install node.js and npm from here. NPM is a package manager used to install javascript packages.

After you have installed node and npm, create a new folder and open a terminal/command-prompt. Next in the terminal/command-prompt change directory into the folder that you created.

Next run the below command in the terminal/command-prompt

npm init

You will now be asked a series of questions, you can accept the defaults for each question. Next  you need to install the express framework, run the following command

npm install express --save

The –save parameter tells npm to save the details of the package to a file call package.json.

Next create a file called index.js and add the below code into it

//create a reference to express.js framework
const express = require('express')
//initilize it
const app = express()

//port to listen on
const port = 3000

//send back hello world when user hits the home page
app.get('/', (req, res) => res.send('Hello World'))

//start listening on port
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

In the above code, we first create a reference to the express framework and then initialize, next we set a route, when a user visits the “/” url, we send them the hello world text. Lastly we start listening on the port for new connections.

Run the below command and open http://localhost:3000/ in a browser

node index.js

You will see the text “Hello world” being displayed in the browser.

Routing

You can create routes in your application to handle requests  to different urls with different HTTP methods.

There are generally 4 methods that are used

Get –  it is used to request data from a specified resource.

Post – It used to send data to a server to create/update a resource.

Put – it is also used to send data to create/update a resource but Put request will always produce the same result. POST requests create the same resource multiple times if it is sent multiple times.

Delete – Used to delete a specified resource.

You can define simple routes in express by using the below syntax

app.HTTP_method((request, response)=>{

})

Where HTTP_method is the http method (get, post, put, delete)

app.route()

You can create chain-able route handlers for a route path by using app.route().

You specify the  route path once and can specify the behavior for the http methods separately, This helps in creating modular routes and reducing redundancy.

Example

app.route('/user')  
.get(function (req, res) { res.send('send User') }) .post(function (req, res) { res.send('create/modify user') }) .put(function (req, res) { res.send('Update a user') })

in the above example, when a get method is made to /user , the first method is called, when a post request is made to the same url , the second method is called and so on.

Serving static files

Express.js can serve static files using the below syntax

express.static(directory, [options])

Where directory is the location of the static files, the method also takes in optionally options. The various options available are available here.

To make express serve the static files, you need to pass it to the app.use function as shown below

app.use(express.static('directory_name'));

If you want, you can also specify a path for all the static files

app.use('path', express.static('directory_name'))

Example

suppose we have an index.html file in a folder called public

app.use(express.static('public'))

The above code will make the index.html file accessible at /index.html

app.use('/pages', express.static('public'))

The above code will make the index.html file accessible at /public/index.html


Also published on Medium.

Share this!

Leave a Reply

Your email address will not be published. Required fields are marked *