我可以一起使用'res.sendFile'和'res.json'吗? [英] Can I use 'res.sendFile' and 'res.json' together?

查看:214
本文介绍了我可以一起使用'res.sendFile'和'res.json'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我在Express应用程序中使用控制器来处理路由。当某个路线被击中时,我打电话给 pagesController.showPlayer ,它为我的 index.html 提供服务。这是控制器:

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
};

我还需要发回一个JSON对象,代表请求此路由的用户。
但是,当我添加 res.json({user:req.user}); 我得到的全部是这个JSON对象, index.html 不再显示。

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.

推荐答案

res.json ()表示Express应用程序在收到HTTP请求时发送的HTTP响应。另一方面, res.sendFile()在给定路径上传输文件。

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.

所以不,你不能使用 res.sendFile res.json 在一起。

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

但是,您确实没有什么办法来达到预期目标:

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

res.sendFile具有以下签名:

res.sendFile have the following signature:

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

其中路径必须是文件的绝对路径(除非在options对象中设置了root选项)。

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

选项中,您可以指定包含HTTP标头的对象以与文件一起提供。

In options, you can specify the object containing HTTP headers to serve with the file.

示例:

  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..


  • 喜欢在cookie中设置内容(但这将是每个后续req / res循环的一部分),或

  • 仅发送一个json响应(带有 res.json )并在客户端管理路由(而nodejs将作为API端),或

  • 设置 res.locals 包含作用于请求的变量的对象,因此仅对在请求/响应周期中呈现的视图(如果有)提供

  • 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)

希望它有帮助!

这篇关于我可以一起使用'res.sendFile'和'res.json'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆