How to use Express to send the response back to the client
In the Hello World example, we usedResponse.send()
To send a simple string as a response and close the connection:
(req, res) => res.send('Hello World!')
If you enter a string, it will setContent-Type
Headertext/html
.
If you pass in an object or array, it will setapplication/json
Content-Type
Header and parse the parameter asJSON format.
send()
auto configurationContent-Length
HTTP response headers.
send()
The connection is also automatically closed.
Use end() to send an empty response
Another way to send a response, without any body, is to useResponse.end()
method:
res.end()
Set HTTP response status
useResponse.status()
:
res.status(404).end()
or
res.status(404).send('File not found')
sendStatus()
Is a shortcut:
res.sendStatus(200)
// === res.status(200).send('OK')
res.sendStatus(403)
// === res.status(403).send('Forbidden')
res.sendStatus(404)
// === res.status(404).send('Not Found')
res.sendStatus(500)
// === res.status(500).send('Internal Server Error')
Download mine for freeExpress.js manual
More crash tutorials:
- Express, the popular Node.js framework
- Use Express to retrieve GET query string parameters
- Use express-validator to validate input in Express
- Express template
- Use Express to serve static assets
- Send JSON response using Express
- Fast meeting
- Send a reply using Express
- Send files using Express
- Use Express-Validator to clean up the input in Express
- Route in Express
- Express HTTPS server with self-signed certificate
- Express, request parameters
- Use Express to retrieve POST query parameters
- Use Express to handle redirects
- Fast middleware
- Set up let's encrypt for Express
- Use HTTP headers in Express
- Processing forms in Express
- Use Express to process file uploads in forms
- Processing CORS in Express
- Use Express to manage cookies