Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Defining Routes | Routing in Express.js
Express.js Essentials for Backend Development

Defining Routes

Scorri per mostrare il menu

When building web applications with Express.js, you define routes to determine how your app responds to client requests for specific endpoints and HTTP methods. A route is essentially a combination of a URL path and an HTTP method (such as GET or POST), paired with a handler function that executes when a request matches.

To define a route in Express, you use methods like app.get() and app.post(). These methods take two main arguments: the path and the handler function. The path is the endpoint you want to respond to, and the handler function receives the request and response objects.

Here is how you can define a simple GET route for the home page, and a POST route for a login endpoint:

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

// Define a GET route for the root path "/"
app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

// Define a POST route for "/login"
app.post('/login', (req, res) => {
  res.send('Login form submitted!');
});

In this example:

  • When a client makes a GET request to the root path /, Express will match it to the first route and execute its handler, sending "Welcome to the homepage!" as the response;
  • When a client submits a POST request to /login, Express matches it to the second route and sends back "Login form submitted!".

Each route in Express is defined by three main parts:

  • The HTTP method: such as GET, POST, PUT, DELETE;
  • The path: the specific endpoint string, such as /, /login, or /users;
  • The handler function: a callback that receives the request (req) and response (res) objects, and sends a response.

Express matches incoming requests to your routes by checking both the HTTP method and the path. If both match, the corresponding handler runs. If no route matches, Express will continue searching or return a 404 error if none is found.

You can also define routes for other HTTP methods like app.put() and app.delete(). This makes it easy to build RESTful APIs or web applications that respond to a variety of actions.

question mark

Which of the following statements about defining routes in Express.js is correct?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 2. Capitolo 1
some-alt