最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use 'res.sendFile' and 'res.json' together? - Stack Overflow

programmeradmin2浏览0评论

Currently I'm using a controller within my Express app to handle routing. When a certain route is hit I call pagesController.showPlayer which serves my 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 need to also send back a JSON object representing the user who is requesting this route. However, when I add res.json({user: req.user}); all I get back is this JSON object, index.html is no longer shown.

Currently I'm using a controller within my Express app to handle routing. When a certain route is hit I call pagesController.showPlayer which serves my 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 need to also send back a JSON object representing the user who is requesting this route. However, when I add res.json({user: req.user}); all I get back is this JSON object, index.html is no longer shown.

Share Improve this question asked Jul 16, 2015 at 17:59 MattDionisMattDionis 3,61610 gold badges54 silver badges109 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

The res.json() represents the HTTP response that an Express app sends when it gets an HTTP request. On the other hand, res.sendFile() transfers the file at the given path.

In both cases, the flow is essentially transferred to client who might have made the request.

So no, you cannot use res.sendFile and res.json together.

However, you do have few workarounds to achieve the desired goal:

res.sendFile have the following signature:

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

Where path must be an absolute path of the file(Unless the root option is set in the options object).

In options, you can specify the object containing HTTP headers to serve 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);

Thats really the closest you can do to achieve the desired task. There are other options too..

  • like setting content in a cookie(but that'll be a part of each subsequent req/res cycle), or
  • sending just a json response (with res.json) and manage routing at client side(while nodejs will serve as an API end), or
  • set res.locals object that contain variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any)

Hope it Helps!

发布评论

评论列表(0)

  1. 暂无评论