Send a reply using Express

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-TypeHeadertext/html.

If you pass in an object or array, it will setapplication/json Content-TypeHeader and parse the parameter asJSON format.

send()auto configurationContent-LengthHTTP 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: