Understanding the res Object in Express.js

William Le

The res object in Express.js, short for response, gives you a simple interface to respond to HTTP requests. In this article, we’ll cover the most important parts of res.

Check-out this sister post if you’re interested in the req counterpart for access to information about the request.

Recommended Node.js video course

Basics of   res

res.send

send is perhaps the most well-known method that’s used on res. With res.send() you can respond to HTTP requests with all sorts of data:

app.get('/home', (req, res) => {
  res.send(Buffer.from('greensnapper'))
  res.send({ crocodiles: ['judy', 'nigel', 'spence'] })  // will convert to a string with JSON.stringify
  res.send('<p>Nice to Eat Ya!</p>')
  res.send('*Splish Splash*')
});

Express.js will automatically append Content-Type and Content-Length headers for the response. Pretty nifty!

res.status

Specify the HTTP status code for the response:

res.status(404).send('Not Found');

// alternatively...
res.sendStatus(404);

HTTP status codes are the quickest way to summarize a server’s response. Browsers rely on HTTP codes for various things like displaying “Not Found” pages, or knowing whether an image should be cached.

res.redirect

res.redirect('/crocodile/local-wetlands')
res.redirect('https://crocs.com')

You can redirect clients to local routes in your app, or to completely different websites.

res.render

app.get('/frogger-game', (req, res) => {
  res.render('frogger.html', {status: 'not-dead'});
});

If you’re building server-rendered websites, this method will send the client HTML pages. If you combine this with a templating language like Pug, Mustache, or EJS you can make data available to your templates. In the above example {status: 'not-dead'} is available as res.locals.status.

res.end

res.end();
res.send();
res.status(404).end();

Use this method to end the response to the client. Sometimes you will want to use this, but generally if you’re using res.send() it will automatically end the response.

Sending Files

Express.js doesn’t just give you simple utilities for sending JSON data and HTML files. You can also send files with res.sendFile():

res.sendFile

// GET https://swamps.com/gallery/my-crib.jpg

app.get('/gallery/:fileName', function (req, res, next) {
  
  var options = {
    root: path.join(__dirname, 'public')
  };

  res.sendFile(req.params.fileName, options, function (err) {
    if (err) next(err);
    else console.log('Sent:', fileName);
  });
});

The image located at https://swamps.com/public/my-crib.jpg will be sent, and prompt the user’s browser to download the image. Simple huh? This isn’t something you’d want to tackle using the low-level http module in Node.js!

A note about the options object. You need to set the “root” or you’ll need to provide an absolute path to your file.

res.download

An alternative way to send a file is to use res.download, which is more concise:

// GET https://swamps.com/gallery/my-crib.jpg

app.get('/gallery/:fileName', function(req, res){
  const file = `${__dirname}/public/${req.params.fileName}`;
  res.download(file);
});

It actually uses res.sendFile under-the-hood so it performs the same actions like prompting the user’s browsers to download the file, as well as setting the appropriate headers (eg., Content-Type: image/jpeg).

Headers

Headers in HTTP are like the sticker that FedEx puts on boxes. These stickers detail various characteristics about your package:

  • Recipient
  • Address to release the package
  • Total weight of package
  • Hazardous material handling
  • Whether to require a signature

Any FedEx driver can hand-off your package to UPS or USPS, and since the sticker follows certain specifications they’ll know how to deliver your package. HTTP Headers are quite similar! They’re metadata that follows W3C guidelines so servers and clients can communicate with each other in seamless harmony.

res.append

res.append('Content-Type', 'application/javascript; charset=UTF-8');
res.append('Connection', 'keep-alive')
res.append('Set-Cookie', 'divehours=fornightly')
res.append('Content-Length', '5089990');

Use this to define any standard/non-standard headers in server responses.

res.type

res.type('png')              // => 'image/png'
res.type('html')             // => 'text/html'
res.type('application/json') // =>'application/json'

This is specifically for defining the Content-Type header. Perhaps one of the most important headers to include in your responses.

Conclusion

There you have it! These are the all the basics you need to know to get rollin’ with res in Express.js. To get comprehensive information about res visit the Express.js official documentation website.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#