Proper way to set response status and JSON content in a REST API made with nodejs and express

前端 未结 12 767
无人及你
无人及你 2020-11-30 20:25

I am playing around with Nodejs and express by building a small rest API. My question is, what is the good practice/best way to set the code status, as well as the response

12条回答
  •  余生分开走
    2020-11-30 20:52

    The best way of sending an error response would be return res.status(400).send({ message: 'An error has occurred' }).

    Then, in your frontend you can catch it using something like this:

            url: your_url,
            method: 'POST',
            headers: headers,
            data: JSON.stringify(body),
        })
            .then((res) => {
                console.log('success', res);
            })
            .catch((err) => {
                err.response && err.response.data && this.setState({ apiResponse: err.response.data })
            })
    

    Just logging err won't work, as your sent message object resides in err.response.data.

    Hope that helps!

提交回复
热议问题