Can I use 'res.sendFile' and 'res.json' together?

I am currently using a controller in my Express app to handle routing. When some route comes up, I call pagesController.showPlayer

which serves mine index.html

. Here is the controller:

'use strict';

var path = require('path');

var player = function(req, res) {
  res.sendFile(path.join(__dirname, '../assets', 'index.html'));
};

module.exports = {
  player: player
};

      

I also need to send back a JSON object representing the user who requests this route. However, when I add res.json({user: req.user});

, whatever I return, this JSON object is index.html

no longer displayed.

+3


source to share


1 answer


res.json()

represents the HTTP response that the express app sends when it receives an HTTP request. On the other hand, it res.sendFile()

transfers the file along the specified path.

In both cases, the stream is essentially passed on to the client who might have made the request.

No, you cannot use res.sendFile

both res.json

.

However, you have few workarounds to achieve your desired goal:

res.sendFile have the following signature:

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

      

Where path

should be the absolute path for the file (unless root is specified in the options object).



In options

you can specify object

containing HTTP headers to work with the file.

Example:

  var options = {
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true,
        'name': 'MattDionis',
        'origin':'stackoverflow' 
    }
  };

res.sendFile(path.join(__dirname, '../assets', 'index.html'), options);

      

This is really the closest thing you can do to achieve your desired goal. There are other options as well.

  • as setting the content in the cookie (but this will be part of every subsequent req / res loop), or
  • sending only the json response (using res.json

    ) and managing client side routing (while nodejs will be used as the end of the API) or
  • set res.locals an object that contains the variables bound to the request and therefore only available to the views displayed during that request / response loop (if any)

Hope it helps!

+7


source







All Articles