首页 > 解决方案 > 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;

标签: javascriptnode.jsroutingmiddleware

解决方案


只需使用,

res.end(myHtml.replace(/jsonapidata/g, JSON.stringify({myJson,apisparkline}, null, 2)));

更好的方法,

res.json({myJson,apisparkline})

然后,在客户端格式化。


推荐阅读