What Does `app.use(express.json())` Do in Express?
Nội Dung Chính
What Does `app.use(express.json())` Do in Express?
The app.use()
function adds a new middleware to the app.
Essentially, whenever a request hits your backend, Express will execute the functions you passed to app.use()
in order.
For example, if you wanted to print the HTTP method and the URL of every request, you would do the following:
const
app = require
('express'
)();
app.use((
req, res, next
) => {
console
.log(`
${req.method}
${req.url}
`);
next();
});
app.get('/test'
, (req, res, next) => {
res.send('ok'
);
});
const
server = await
app.listen(3000
);
const
axios = require
('axios'
);
await
axios.get('http://localhost:3000/test'
);
Using express.json()
express.json()
is a built in middleware function in Express starting from v4.16.0.
It parses incoming JSON requests and puts the parsed data in req.body
.
const
express = require
('express'
);
const
app = express();
app.use(express.json());
app.post('/test'
, function
(req,res
) {
console
.log(`
${req.body}
`);
});
const
server = await
app.listen(3000
);
const
axios = require
('axios'
);
await
axios.post('http://localhost:3000/test'
, { answer
: 42
});
Using the limit option in express.json()
The limit
option allows you to specify the size of the request body.
Whether you input a string or a number, it will be interpreted as the maximum size of the payload in bytes.
app.use(express.json({ limit
: 10
}));
const
app = require
('express'
)();
app.use(express.json({ limit
: 1
}));
app.post('/limit-break'
, (req, res, next) => {
console
.log(req.body);
res.send('ok'
);
});
const
server = await
app.listen(3000
);
const
axios = require
('axios'
);
const
res = await
axios.post('http://localhost:3000/limit-break'
, {
name
: 'Mastering JS'
,
location
: 'Florida'
,
helpful
: true
});
Want to become your team’s Express expert? There’s no better way to really grok a framework than to write your own
clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express
called Espresso.
Get your copy!
Espresso supports:
- Route handlers, like `app.get()` and `app.post()`
- Express-compatible middleware, like `app.use(require(‘cors’)())`
- Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.
Get the tutorial and master Express today!