- Advanced Node.js Development
- Andrew Mead
- 192字
- 2021-08-27 19:06:05
Setting up HTTP status code
If you remember, HTTP statuses let you give someone some information about how the request went. Did it go well? Did it go poorly? That kind of thing. You can get a list of all the HTTP statuses available to you by going to httpstatuses.com. Here, you can view all of the statuses that you can set:
The one that's set by default by Express is 200. This means that things went OK. What we're going to be using for an error is code 400. A 400 status means there was some bad input, which is going to be the case if the model can't be saved. Maybe the User didn't provide a text property, or maybe the text string was empty. Either way, we want to send a 400 back, and that's going to happen. Right before we call send, all we're going to do is call status, passing in the status of 400:
todo.save().then((doc) => { res.send(doc); }, (e) => { res.status(400).send(e); });
With this in place, we are now ready to test out our POST /todos request over inside of Postman.