req.body in the next middleware?app.use(express.json());
app.use((req, res, next) => {
if (req.body && req.body.name) {
req.body.name = req.body.name.trim().toUpperCase();
}
next();
});
app.post('/test', (req, res) => {
res.json({ transformedName: req.body.name });
});req.body.name before the final handler.The middleware trims whitespace and converts the name to uppercase. So sending {"name": " alice "} results in "ALICE".
timestamp with the current time before handling the request. Which code snippet correctly does this in Express?req.body as an object.Option B and D use express.json() middleware to parse JSON bodies, then add the timestamp and call next(). Option A tries to parse req.body again causing error. Option C uses urlencoded parser which is wrong for JSON.
app.use((req, res, next) => {
req.body.name.toUpperCase();
next();
});
app.post('/user', (req, res) => {
res.json({ name: req.body.name });
});toUpperCase() work in JavaScript.Strings are immutable in JavaScript. toUpperCase() returns a new string but does not change the original. The middleware must assign the result back to req.body.name.
req.body after this middleware chain?req.body contain when the final handler runs?app.use(express.json());
app.use((req, res, next) => {
req.body = { ...req.body, added: true };
next();
});
app.use((req, res, next) => {
delete req.body.removed;
next();
});
app.post('/data', (req, res) => {
res.json(req.body);
});removed property is deleted.The first middleware copies req.body and adds added: true. The second middleware deletes removed property. So the final object has name and added, but no removed.
req.body directly in middleware can be risky?req.body in middleware cause unexpected issues in later handlers or middleware?Middleware share the same req object. Changing req.body directly can break other middleware or handlers that expect the original data format.