Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Using Built-in Middleware | Middleware in Express.js
Express.js Essentials for Backend Development

Using Built-in Middleware

Stryg for at vise menuen

Express.js provides several built-in middleware functions that help you handle common web application tasks with minimal setup. Two of the most widely used built-in middleware are express.json() and express.static(). These middleware functions simplify handling incoming request data and serving static assets like images, CSS, and JavaScript files.

To see how these middleware work in practice, consider this example of a simple Express app that uses both express.json() and express.static():

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

// Use express.json() to parse incoming JSON requests
app.use(express.json());

// Serve static files from the "public" directory
app.use(express.static('public'));

app.post('/api/data', (req, res) => {
  // Access parsed JSON data from the request body
  const data = req.body;
  res.json({ received: data });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, express.json() is added as middleware to the app using app.use(). This middleware parses incoming request bodies in JSON format and makes the resulting object available on req.body. When a client sends a POST request with a JSON payload to the /api/data endpoint, you can directly access the parsed data as a JavaScript object.

The express.static() middleware is also used with app.use(), pointing to the "public" directory. This allows the app to serve static files—such as HTML, CSS, images, or JavaScript—directly from that directory. For instance, if you place a file called logo.png in the "public" folder, it becomes accessible at http://localhost:3000/logo.png without needing to define a separate route.

To summarize, express.json() parses the body of incoming requests with a Content-Type of application/json, enabling you to easily handle JSON data sent by clients. express.static() serves static files from a specified directory, allowing you to efficiently deliver assets to users without writing custom route handlers for each file.

question mark

Which statement best describes the purpose of Express.js built-in middleware like express.json() and express.static()?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 3. Kapitel 2
some-alt