javascript - NodeJS 中间件/路由数据传输
问题描述
您好,我正在尝试将更多数据传输到客户端。我在 NodeJS express 中使用了中间件的示例代码。
我想读取 2 个不同的文件并将数据传输到客户端。我已成功传输 1 个文件数据。如何添加多个?
我该怎么做?,我尝试了“发送”和“json”,但我看不到网站的前端
var express = require('express');
var router = express.Router();
const fs = require('fs');
/* GET home page. */
// const myHtml = require('fs').readFileSync(<path to html>);
const myHtml = fs.readFileSync('./views/index.html', 'utf-8');
//Data from server to client, this works.
const myJson = fs.readFileSync("./apidata.json", 'utf-8');
//I want to add a second one here
const apisparkline = fs.readFileSync("./apisparkline.json", 'utf-8');
console.log("server is running");
router.get('/', function(req, res, next) {
//This works perfect
res.end(myHtml.replace(/jsonapidata/g, JSON.stringify(myJson, '', 2)));
//how should I do this?, I have tried 'send' and 'json' but then I cant see my front end of the website
res.end(myHtml.replace(/sparklinedata/g, JSON.stringify(apisparkline, '', 2)));
});
module.exports = router;
解决方案
只需使用,
res.end(myHtml.replace(/jsonapidata/g, JSON.stringify({myJson,apisparkline}, null, 2)));
更好的方法,
res.json({myJson,apisparkline})
然后,在客户端格式化。
推荐阅读
- pyspark - 如何在数据框的开头移动 pyspark 数据框的特定列
- android - 使用 recyclerview 和改造未显示获取的数据
- docker - 你如何在 docker 上设置 Filebeat?
- reactjs - 挂载组件时无法加载模拟数据
- javascript - vue js大数组到表性能建议
- python - 使用 Django admin 在具有字段定义的模型中导入 json 文件
- java - 尽管存储了 RecyclerView,但它仍丢失 Checkbox 状态
- api - Razorpay PHP 集成问题
- java - 在 Android Marshmallow 设备中使用 HTTP Apache 客户端运行为 Android Kitkat 制作的 APK
- excel - 在工作表上的两个选定列中查找唯一值