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:
(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:
res.end()
To set the HTTP response status, you can use the Response.status()
method. Here are a few examples:
res.status(404).end()
or
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:
res.sendStatus(200)
// Equivalent to: res.status(200).send('OK')
res.sendStatus(403)
// Equivalent to: res.status(403).send('Forbidden')
res.sendStatus(404)
// Equivalent to: res.status(404).send('Not Found')
res.sendStatus(500)
// Equivalent to: res.status(500).send('Internal Server Error')
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