Performance: Built-in middleware (json, urlencoded, static)
This affects the server response time and initial page load speed by handling request parsing and static file delivery efficiently.
app.use(express.json());
app.use((req, res, next) => {
let data = '';
req.on('data', chunk => { data += chunk; });
req.on('end', () => {
try {
req.body = JSON.parse(data);
} catch (e) {
return next(e);
}
next();
});
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual JSON parsing | N/A | N/A | N/A | [X] Bad |
| express.json() middleware | N/A | N/A | N/A | [OK] Good |
| Manual URL-encoded parsing | N/A | N/A | N/A | [X] Bad |
| express.urlencoded() middleware | N/A | N/A | N/A | [OK] Good |
| Manual static file serving | N/A | N/A | N/A | [X] Bad |
| express.static() middleware | N/A | N/A | N/A | [OK] Good |
express.json() is designed to parse JSON data sent in request bodies.express.urlencoded() parses URL-encoded form data, express.static() serves files, and express.bodyParser() is not a built-in middleware.express.urlencoded() is a function that returns middleware and accepts an options object.{ extended: true } to support rich objects and arrays./public/image.png if the file exists?
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/', (req, res) => res.send('Home'));
app.listen(3000);express.static('public') serves files from the 'public' folder when requested by path./public/image.png looks for public/public/image.png which does not exist. But since the middleware serves files relative to the folder, the correct URL to access image.png is /image.png./public/image.png will cause 404 because the middleware serves files at root, not under /public.const express = require('express');
const app = express();
app.use(express.json);
app.use(express.urlencoded({ extended: false }));
app.listen(3000);express.json() must be called with parentheses to return the middleware function.express.json without parentheses, so it passes the function itself, not the middleware, causing an error.assets under the URL path /static. Which Express middleware setup achieves this correctly?app.use('/urlpath', express.static('folder')).assets and the URL path is /static, so app.use('/static', express.static('assets')) is correct.Pass the test and this pattern moves unknown