简体   繁体   中英

ExpressJS - What happens when .json() is used in with a response?

I was making a server using ExpressJS and this thing is really bugging me. What is the use of using .json() instead of .send() with my responses. According to Express, .send() automatically coverts the JavaScript objects into JSON strings and we do not need to use stringify.Then why use .json() with my responses.

app.get('/profile/:id', (req, res) => {
const {id} = req.params;
let found = false;
database.users.forEach(user => {
    if(user.id === id) {
        found = true;
        return res.json(user);
    }
})
if (found === false)
{
    res.status(400).json('not found');
}
})

Here is the code where res.json() apppears.

well in the end res.json calls res.send , and they both are identical when you pass an object or array.

But res.json method also uses json replacer and json spaces settings. They give you more flexibility and options to format your json file. also res.json makes sure the response is in utf8 charset.

To better understand the differences I recommend you to check : Difference between res.send and res.json in Express.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM