How to Send a Response Using Express
In this blog post, we will discuss how to send a response back to the client using Express. When building web applications with Express, it is important to understand how to send the appropriate response to the client based on the request.
In the previous Hello World example, we used the Response.send()
method to send a simple string as a response and close the connection. For example:
1 | (req, res) => res.send('Hello World!') |
By passing in a string as the parameter, the Content-Type
header is automatically set to text/html
.
If you want to send an object or an array as the response, the send()
method sets the Content-Type
header to application/json
and parses the parameter into JSON.
The send()
method also automatically sets the Content-Length
HTTP response header and closes the connection.
Alternatively, you can use the Response.end()
method to send an empty response without any body. For example:
1 | res.end() |
To set the HTTP response status, you can use the Response.status()
method. Here are a few examples:
1 | res.status(404).end() |
or
1 | res.status(404).send('File not found') |
There is also a shortcut method called sendStatus()
, which allows you to set the HTTP response status and send a corresponding message in one line of code. Here are a few examples:
1 | res.sendStatus(200) |
And there you have it! Now you know how to send a response back to the client using Express. Happy coding!
Tags: Express, Response, HTTP response, send, end, status, sendStatus