Returning a response
Our server accepts requests, does some stuff, and finally, sends the response to the client's browser. This can be HTML, JSON, XML, or binary data, among others. As we know, by default, every middleware in Express accepts two objects, request
and response
. The response
object has methods that we can use to send an answer to the client. Every response should have a proper content type or length. Express simplifies the process by providing functions to set HTTP headers and sending content to the browser. In most cases, we will use the .send
method, as follows:
res.send("simple text");
When we pass a string, the framework sets the Content-Type
header to text/html
. It's great to know that if we pass an object or array, the content type is application/json
. If we develop an API, the response status code is probably going to be important for us. With Express, we are able to set it like in the following code snippet:
res.send(404, 'Sorry, we cannot find...