简体   繁体   中英

What is .json() used for in error handling?

I am learning error handling and am not quite sure what .json() does. Is it just storing information of .status() ? Is it a way of displaying information elsewhere? The MDN docs are not very clear. They say it returns a promise. Not sure how that applies in this context. If someone could point me in the right direction I would appreciate it!

Here is just a segment of code when building my CRUD operations.

deleteMovie = async (req, res) => {
    await Movie.findOneAndDelete({ _id: req.params.id }, (err, movie) => {
        if (err) {
            return res.status(400).json({ success: false, error: err })
        }

        if (!movie) {
            return res
                .status(404)
                .json({ success: false, error: `Movie not found` })
        }

        return res.status(200).json({ success: true, data: movie })
    }).catch(err => console.log(err))
}

Corrected: The documentation you're looking for is here: https://expressjs.com/en/api.html#res.json in the Express API docs. The.json() method is used to parse the response data and convert it to the friendly JSON format you will likely want to use in your app. Expect to see.json() used on many responses, not just errors.

Is it just storing information of.status()

No. It's not used for error handling either. The result from .status is chained though . and .json further returns aa response of JSON object

Rather than a part of error handling, the json method is used in the response handling. It is one of the methods in Express Response Object.

This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

You can take it as a shortcut to the following code

res.set('content-type', 'application/json');
res.send(JSON.stringify({"foo":"bar"}));

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