Using Built-in Middleware
Pyyhkäise näyttääksesi valikon
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.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme