Examples


Express.js - Routes


In this tutorial we see how to create and manage routes in Express.js and HTTP methods, route handling to build efficient web applications and APIs using Express.js.

Routes in Express.js

Routes is defined how an application responds to different client requests for specific URLs or paths. Each route is associated with a specific HTTP method like GET, POST, PUT, DELETE and is used to handle different types of requests, allowing the server to perform various actions based on the request type.

Syntax for Defining a Route

app.METHOD(PATH, HANDLER)
  • METHOD - The HTTP method (GET, POST, PUT, DELETE).
  • PATH - The route (URL) that the client is requesting.
  • HANDLER - A callback function that processes the request and sends the response.

Example of Routes Method

app.get('/users', (req, res) => {
    res.send('GET request to the users page');
});

app.post('/users', (req, res) => {
    res.send('POST request to add a new user');
});

app.put('/users/:id', (req, res) => {
    res.send(`PUT request to update user with ID ${req.params.id}`);
});

app.delete('/users/:id', (req, res) => {
    res.send(`DELETE request to remove user with ID ${req.params.id}`);
});

Key Components of a Route in Express.js

  • HTTP Method - GET, POST, PUT, DELETE
  • Path/URL - The endpoint (URL) that the client is requesting.
  • Request (req) - Contains information about the HTTP request.
  • Response (res) - Used to send back the desired output to the client.

Route Methods

  • app.get() - Handles GET requests (fetching data).
  • app.post() - Handles POST requests (creating data).
  • app.put() - Handles PUT requests (updating data).
  • app.delete() - Handles DELETE requests (removing data).
  • app.all() - Handles all HTTP methods for the specified path.

Prev Next