What is express.json() — A Quick Overview
When someone sends data to the server, they often send it in a certain format. One common format is JSON (which stands for JavaScript Object Notation). This is a way to represent data like:
{
"name": "John",
"age": 30
}
Now, when server receives this data, it needs to understand it. Without the right tool, it would just look like a bunch of text.
What does express.json()
do?
express.json()
is like a helper for the server that converts this text (JSON data) into something the server can understand and work with easily (a JavaScript object).
When a client sends a request with JSON data, like:
{
"name": "John",
"age": 30
}
Without express.json()
, the server wouldn't know how to handle that data. But when we use app.use(express.json())
, it automatically converts the JSON data into a JavaScript object so we can access it easily, like this:
app.post('/user', (req, res) => {
console.log(req.body); // { name: 'John', age: 30 }
});
So in short, express.json()
is used to automatically convert JSON data from the request into a JavaScript object, making it easy to work with.