Horje
How Express Works?

ExpressJS is a fast and minimal web application framework that is built on top of NodeJS. It provides a robust set of features such as handling HTTP requests, implementing middleware, routing etc. which can be utilized to build dynamic web applications, mobile applications and implement APIs.

It is a thin, lightweight and flexible framework core web application features. Additional features can be added through the use of Express middleware modules. In this article, we will explore how Express works.

Prerequisites:

Installing Express:

Step 1: Initialize and Node.js project

mkdir express-app
cd express-app
npm init -y

Step 2: Install Express using npm

npm install express
npmiexpress

To add express to a pre-existing node project,

Step 3: Add express to the dependencies in package.json

package

package.json

Step 4: Install all the dependencies using `npm install`

npm-install

npm install

Usage of Express:

Depending on an application’s requirements, Express.js can be used in various ways such as:

  1. Creating a basic server
  2. Implementing middleware
  3. Routing
  4. Handling HTTP requests
  5. Integrating with databases.

Creating a Basic Server

To create an Express server, initialize a node.js project and install express following the installation guide. Then create an app instance and define a port for the server to listen on as show in the following code:

JavaScript
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Server is online!');
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
basicServer

basic Express server

To run the server use the command:

 `node <filename>.js`

Implementing middleware

Middleware function are functions that have access to the request object and are executed before the requests are handled. Middleware functions can be added using `app.use(middleware)`

JavaScript
const express = require('express');
const app = express();

app.use((req, res, next) => {
    console.log('Middleware function executed');
  next();
});

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
middleware

adding middleware

The middleware function is executed every time a request is sent to the server.

Creating Routes

Routes can be defined as endpoints of an application that are utilized to describe how the server responds to client’s requests. routes can be create using `app.[HTTP Method](<routename>, handler function)`. example:

JavaScript
const express = require('express');
const app = express();

app.get('/about', (req, res) => {
    console.log('accessed about us page');
    res.send('About Page');
});

app.get('/contact', (req, res) => {
    console.log('accessed contact us page');
    res.send('Contact Page');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Here when a request is sent to `http:localhost:3000/about` the handler function corresponding to the route is executed.

routes

creating routes

Handling HTTP methods

Express allows you to handle various HTTP methods like GET, POST, PUT, DELETE, etc. as follows:

JavaScript
const express = require('express');
const app = express();

app.post('/submit', (req, res) => {
    res.send('Form Submitted');
});

app.put('/update', (req, res) => {
    res.send('Data Updated');
});

app.delete('/delete', (req, res) => {
    res.send('Data Deleted');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
HTTP-methods

handling HTTP methods

Functioning of these routes be tested using dev tools such as postman or using a browser.

Integrating with Databases

Express be integrated with databased such as MongoDB, MySQL, PostgreSQL to store and perform operations on data.

JavaScript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

mongoose.connect('mongodb://localhost:27017/mydatabase');

const Schema = mongoose.Schema;
const StudentSchema = new Schema({
    name: String
});

const Student = mongoose.model('Student', StudentSchema);

app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.get('/students', async (req, res) => {
    try {
        const students = await Student.find({}, 'name');
        res.json(students);
  } catch (error) {
        res.status(500).send(error);
  }
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
mongoDB

fetching data from MongoDB

Why Use Express?

  1. Minimalist Framework: Express does not enforce a particular way of structuring your application.
  2. Robust Routing: It provides a robust routing mechanism for handling different HTTP requests.
  3. Middleware Support: Allows for easy integration of middleware to process requests and responses.
  4. Performance: Built on top of Node.js, it uses its asynchronous, non-blocking nature for high performance.
  5. Community and Ecosystem: A vast and active community contributes to a rich ecosystem of middleware and plugins.

Conclusion

Express.js simplifies the process of building web applications by providing a powerful framework that handles routing, middleware, HTTP methods, and integrates well with databases

Frequently Asked Questions (FAQs)

How does Express handle multiple requests?

Express handles multiple requests asynchronously by default. Each incoming request is processed independently. And callbacks or promises are utilized to handle the asynchronous operations

How can I handle errors in Express.js applications?

Errors in Express.js servers can be handled by either using try-catch blocks in the request handler’s logic or declaring middlewares to handle the error.

How can I handle file uploads in Express.js?

File uploads can be handled on Express.js servers using middleware such as ‘multer’ which enables us to handle multipart/form-data, which is typically used for file uploads.




Reffered: https://www.geeksforgeeks.org


Express.js

Related
Express Routing in MERN Stack Express Routing in MERN Stack
Passing Data to EJS Templates Passing Data to EJS Templates
Music Playlist Manager with Node.js and Express.js Music Playlist Manager with Node.js and Express.js
Subscription Management System with NodeJS and ExpressJS Subscription Management System with NodeJS and ExpressJS
Budget Tracking App with Node.js and Express.js Budget Tracking App with Node.js and Express.js

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16