Introduction to Express js

So what is Express?

ยท

2 min read

Express is a node.js web application framework. It is an unopinionated web framework, what exactly is the meaning of unopinionated? It means that there are no specific rules or restrictions on the best way to put your components together. Express is written in Js and hosted within the node.js runtime environment. It is the most popular node.js framework.

Features of Express

It provides mechanisms to:

  1. write handlers for requests with different http vers, i.e get, post, put, delete

  2. intergrate with view engines to render web pages using template files e.g Embedded js(EJS)

  3. set the port you want to use for local development and the location of the templates.

  4. add middleware, these are used to process request objects multiple times before the server works for that request.

How does Express work?

Express works by providing methods to specify which function will be called for a given HTTP verb, the route, and the template that will be used.

Install Express

Using npm

npm install express

using yarn

yarn add express

Express Hello World

// import express module 
const express = require('express')
// reate an express app
const app = express() 
const port =5000

// route
app.get('/', (req, res), {
    res.send('Hello World')
})
app.listen(port, () => console.log(`Listening on port ${port}`))

Handling routes in express

To handle a route, callback functions are used. These will handle requests for a given route.

app.METHOD(path, routeHandler)

For example, in the above code when a user goes to the '/' route they get the text 'Hello World'.

app.get('/', (req, res), {
    res.send('Hello World')
})

A callback function takes 2 arguments:

  1. request (req), HTTP request

  2. response, HTTP response sent by the express app when it gets the HTTP request

Middleware

Middleware is just a function that performs some operation on the request or response and then calls the next function in the stack. They can be used to:

  • handle errors

  • compress HTTP responses

  • serve static files etc

Middleware can be used for specific routes or by all the routes in the whole application. To set a middleware function only for a specific route, set it as the second parameter for that route.

const middlewareFunction = (req, res, next) => {
    // do something
    next()
})
app.get('/', (req, res), {
    res.send('Hello World')
})

app.get('/', middlewareFunction, (req, res) => res.send('Hello world))

To be used by all the app's routes:

app.use(middlewareFunction)

Conclusion

Express is a great framework as it enables you to define routes easily and handle HTTP requests. Thus it is good for building APIs