Menu Close

Guide to the Express Response Object — Sending Things

The Express response object lets us send a response to the client.

Various kinds of responses like strings, JSON, and files can be sent. Also, we can send various headers and status code to the client in addition to the body.

In this article, we’ll look at various properties of the response object, including send , sendFile , and sendStatus .

Methods

res.send([body])

We can use the res.send method to send an HTTP response.

The body parameter can be a Buffer object, string, a plain object or an array.

For example, we can send a binary response by writing:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.send(Buffer.from('foo'));  
})  
app.listen(3000);

To send JSON, we can pass in an object:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))app.get('/', (req, res, next) => {  
  res.send({ foo: 'bar' });  
})  
app.listen(3000);

We can also send HTML by passing in a string:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))app.get('/', (req, res, next) => {  
  res.send('<p>foo</p>');  
})  
app.listen(3000);

We can send the response code in addition to the send method:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.status(404).send('not found');  
})
app.listen(3000);

We can set the response header before sending our response:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.set('Content-Type', 'text/html');  
  res.send(Buffer.from('<p>foo</p>'))  
})  
app.listen(3000);

send also works with an array:

const express = require('express')  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.send([1, 2, 3]);  
})
app.listen(3000);

Then we get [1,2,3] .

res.sendFile(path [, options] [, fn])

We can use the sendFile to send a file with various options specified in the options object.

An absolute path is required for the path for sendFile to work.

For example, we can use it as follows:

const express = require('express');  
const path = require('path');  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  const options = {  
    root: path.join(__dirname, 'files'),  
    dotfiles: 'deny',  
    headers: {  
      'x-timestamp': Date.now(),  
      'x-sent': true  
    }  
  }  
  res.sendFile('foo.txt', options);  
})  
app.listen(3000);

The code above sets the root path in the options so that we don’t have to construct the absolute path every time we call sendFile .

The following properties can be added to the options object:

  • maxAge — sets the max-age property of the Cache-Control header in milliseconds or a string in ms format
  • root — root directory for relative filenames
  • lastModified — sets the Last-Modified header to the last modified date of the file on the OS. Set to false to disable it.
  • headers — an object containing HTTP response headers to serve with the file.
  • dotfiles — option for serving dotfiles. Possible values are allow , deny , or ignore .
  • acceptRanges — enable or disable accepting range requests
  • cacheControl — enable or disable setting Cache-Control response header
  • immutable — enable or disable immutable directive in the Cache-Control header. If it’s enabled, the maxAge option should be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of maxAge option to check if a file has changed.

We can also pass in a callback to handle errors as the last argument:

const express = require('express');  
const path = require('path');  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  const options = {  
    root: path.join(__dirname, 'files'),  
    dotfiles: 'deny',  
    headers: {  
      'x-timestamp': Date.now(),  
      'x-sent': true  
    }  
  }  
  res.sendFile('foo.txt', options, err => next(err));  
})  
app.listen(3000);

res.sendStatus(statusCode)

We can send an HTTP response status code with this method. We just have to pass in a number.

If an unsupported status code is specified the code will still be sent and a string version of it will be sent in the response body.

For example, if we have:

const express = require('express');  
const path = require('path');  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.sendStatus(200)  
})  
app.listen(3000);

Then we get back OK .

If we write the following:

const express = require('express');  
const path = require('path');  
const app = express()  
app.use(express.json())  
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res, next) => {  
  res.sendStatus(900)  
})  
app.listen(3000);

We get 900 since we sent an unsupported response code.

Conclusion

We can send responses in various ways with Express. The most generic one is send , which lets us send both textual and binary data. We can set headers to indicate what we’re sending.

sendFile sends a file response with the absolute file path of the file on the server. We can specify various options for the file we send.

The sendStatus method lets us send an HTTP response code only. We can use it to send both supported and unsupported response codes.

Posted in Express, expressjs