Introduction To Express Framework

Introduction To Express Framework

Play this article

Table of contents

Express is a web application framework for Node.js, used for building server-side applications. It provides a minimal interface for building APIs and web applications, allowing for flexibility and ease of use.

Node.js on the other hand is a runtime environment for JavaScript, which allows you to run JavaScript code on the server side. Express is built on top of Node.js and provides additional features for building web applications.

One of the key differences between Node.js and Express is the way they handle HTTP requests. In Node.js, you have to manually manage HTTP requests and responses using the core http module. Express simplifies this process by providing a high-level API for handling HTTP requests and responses, making it easier to write and maintain your application.

Express provides a number of features including:

  • Routing: mapping incoming requests to specific handlers based on URL and HTTP method

  • Middleware: functions that can modify or augment the behavior of an incoming request before it is processed

  • Template engine integration: allowing you to render dynamic HTML pages based on data from your application

  • Easy-to-use HTTP utility methods: making it simple to send JSON responses, static files, or perform redirects

Express has a large and active developer community, which has contributed a wealth of plugins and extensions to the framework, making it easy to add new functionality and extend its capabilities.

Express is a popular and widely-used open-source framework for building server-side applications in Node.js. It is designed to make it easy for developers to create robust and scalable APIs for their web applications.

One of the key features of Express is its flexibility, allowing developers to create a wide range of applications from simple, single-page websites to complex and sophisticated backends. It also provides a set of powerful and convenient middleware functions that can be used to handle tasks such as parsing requests, handling cookies, and rendering views.

Express also provides a simple and intuitive routing system, making it easy for developers to handle incoming requests and route them to the appropriate controllers. This allows for the separation of concerns and the creation of clean and maintainable code.

In terms of performance, Express is fast and efficient, and it can handle a high number of concurrent requests without sacrificing performance. This is due to its use of Node.js and its ability to handle multiple requests asynchronously.

Let's implement an HTTP request using both node js and express framework in writing the code

//fixtures.js
//Let's create some JSON Data
const books = [
    {
        title: "The Design of Everyday Things",
        author: "Don Norman",
        year: 2014,
        id: 1
    },
    {
        title: "Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming",
        author: "Marijn Haverbeke",
        year: 2014,
        id: 2
    },
    {
        title: "Algorithms to Live By",
        author: "Brian Christian and Thomas L. Griffiths",
        year: 2016,
        id: 3
    }
];

const authors = [
    {
        name: "Don Norman",
        country: "USA",
        id: 1
    },
    {
        name: "Marijn Haverbeke",
        country: "Netherlands",
        id: 2
    },
    {
        name: "Brian Christian and Thomas L. Griffiths",
        country: "USA",
        id: 3
    }
];

module.exports = {
    books,
    authors
};

Nodejs

const http = require('http');
const { authors, books } = require('./fixtures')

const PORT = 3000
const HOST_NAME = 'localhost';

const requestHandler = function (req, res) {
    res.setHeader("Content-Type", "application/json");
    console.log(url)
    console.log(req.method)

    switch (req.url) {
        case '/books':
            res.end(JSON.stringify(books));
            break;
        case '/authors':
            res.end(JSON.stringify(authors));
            break;
        default:
            res.writeHead(404);
            res.end(JSON.stringify({
                message: 'Not Found'
            }))        
    }
}

const server = http.createServer(requestHandler)

server.listen(PORT, HOST_NAME, () => {
    console.log(`Server is listening on ${HOST_NAME}:${PORT}`)
})

This code creates a simple HTTP server using the 'http' module in Node.js. The server listens on localhost at port 3000.

The code imports two objects, authors and books, from a file named fixtures and creates a request handler function to handle incoming requests.

The request handler function sets the response header's content type to application/json and logs the URL and method of the incoming request.

Then, it uses a switch statement to check the URL of the incoming request and returns the appropriate JSON response, either authors or books objects, depending on the URL. If the URL does not match either /books or /authors, it returns a JSON object with a 404 status code and a message property with the value of 'Not Found'.

Finally, it creates an HTTP server instance using http.createServer and passes the request handler function as an argument. The server listens on port 3000 at localhost and logs a message to the console when it starts listening.

Expressjs

const express = require('express')
const { authors, books } = require('./fixtures')


const PORT = 4000
const app = express()


app.get('/books', (req, res) => {
    res.status(200).json({
        status: true,
        books
    })
})

app.get('/authors', (req, res) => {
    res.status(200).json({
        status: true,
        authors
    })
})

app.get('/', (req, res) => {
    res.status(200).send("Welcome to the Home page")
})

app.get('*', (req, res) => {
    res.send("This Route does not exist")
})

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`)
})

We can see that from both codes above, it is easier and cleaner to implement it using express than nodejs, and also writing complex code can be tedious and hectic with node.

Conclusion

In conclusion, Express is a crucial tool for backend developers, allowing them to create scalable and robust APIs with ease. Its flexibility, performance, and ease of use make it an ideal choice for a wide range of applications, from small personal projects to large enterprise systems.

Did you find this article valuable?

Support Edet Asuquo by becoming a sponsor. Any amount is appreciated!