response.status(code):
- This method sets the HTTP status code for the current response.
- It does not send the response immediately, but only sets the status code. You still need to call another method, such as response.send(), response.json(), or response.render(), to actually send the response.
- Example usage:
javascript res.status(404).send('Not Found');
response.sendStatus(code):
- This method combines setting the status code and sending the response with the corresponding text message.
- It automatically sends the response with the specified HTTP status code and the corresponding text message, which will be used as the response body.
- Example usage:
javascript res.sendStatus(404); // Sends a response with HTTP code 404 and the text "Not Found"
Key differences:
- response.status() sets the status code but does not send the response, while response.sendStatus() sets the status code and sends the response.
- response.status() should be used when you want to set the status code and then send the response using another method, such as response.send() or response.json().
- response.sendStatus() is useful when you need to quickly send a response with a certain status code and a standard text message.
In general, the choice between response.status() and response.sendStatus() depends on your specific situation and how you want to structure your responses.