Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 节点+;Express+;Swig/将本地json文件传递给模板_Javascript_Node.js_Express_D3.js_Swig Template - Fatal编程技术网

Javascript 节点+;Express+;Swig/将本地json文件传递给模板

Javascript 节点+;Express+;Swig/将本地json文件传递给模板,javascript,node.js,express,d3.js,swig-template,Javascript,Node.js,Express,D3.js,Swig Template,我是一个node noob,我能够让express/swig玩得很好,并在屏幕上显示,当我介绍我的d3代码(它自己工作)时,控制台返回uncaughttypeerror:cannotread属性'forEach'的未定义(匿名函数)@json:63event@d3.js:504respond@d3.js:1942 需要注意的是,data.json与模板位于同一目录中 我是不是走错了路?在节点内部进行d3渲染会更好吗?如果是,如何将其传递给swig模板等? 编辑-我注意到在开发工具中没有检索jso

我是一个node noob,我能够让express/swig玩得很好,并在屏幕上显示,当我介绍我的d3代码(它自己工作)时,控制台返回
uncaughttypeerror:cannotread属性'forEach'的未定义(匿名函数)@json:63event@d3.js:504respond@d3.js:1942

需要注意的是,
data.json
与模板位于同一目录中

我是不是走错了路?在节点内部进行d3渲染会更好吗?如果是,如何将其传递给swig模板等?

编辑-我注意到在开发工具中没有检索json,但是SVG呈现。我评论了以下内容,因为express劫持了get

// app.get('/*', function (req, res) {
//  res.send("404 bro");
// });
现在又出现了一个新的错误,这是一个好迹象

GET http://localhost:3000/templates/data.json 404 (Not Found)
再一次,对不起,我有点像一个node nooby

更新-这是我的更新代码

var data = require('./templates/data/data.json');
console.log("====== Loaded Jason ======" +  JSON.stringify(data));

app.get('/json', function(req, res){
    res.render('line', {'title' : 'First Swig Template'});
    res.sendFile(data);
});
app.get('/json', function(req, res){
    res.render('line', {'title' : 'First Swig Template'});
    res.sendFile('data.json', { root: path.join(__dirname, '/templates/data') });
});
它带着

Unhandled rejection TypeError: undefined is not a function
更新-这是我的更新代码

var data = require('./templates/data/data.json');
console.log("====== Loaded Jason ======" +  JSON.stringify(data));

app.get('/json', function(req, res){
    res.render('line', {'title' : 'First Swig Template'});
    res.sendFile(data);
});
app.get('/json', function(req, res){
    res.render('line', {'title' : 'First Swig Template'});
    res.sendFile('data.json', { root: path.join(__dirname, '/templates/data') });
});
这是一个很好的例子

Error: Can't set headers after they are sent.
Json现在显示在屏幕上。

节点代码

// Retrieve
var MongoClient = require('mongodb').MongoClient;
//Swig for template
var swig = require('swig');
//consolidate -templating consolidation library
var cons = require("consolidate");
// Express
var express = require('express');
var app = express();

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/templates');

app.get('/swig', function(req, res){
    res.render('home', {'title' : 'First Swig Template'});
});
app.get('/json', function(req, res){
    res.render('line', {'title' : 'First Swig Template'});
});
//setup routes
app.get('/*', function (req, res) {
    res.send("404 bro");
});
//setup server
var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

});


// Connect to the db
MongoClient.connect("mongodb://localhost:27017/linejson", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }

  var collection = db.collection('dummy');

 // count records
    collection.count(function(err, count) {
          console.log("There are " + count + " records.");
        });
    collection.find().each(function(err, doc) {
          if(doc != null) console.log("Doc from Each ");
          console.dir(doc);
        });
});
Html模板+D3代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Data Visualization with D3 </title>
        <!-- Bootstrap CDN CSS -->
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
        <style> /* set the CSS */
        body { font: 12px Arial;}
        path {
        stroke: steelblue;
        stroke-width: 2;
        fill: none;
        }
        .axis path,
        .axis line {
        fill: none;
        stroke: grey;
        stroke-width: 1;
        shape-rendering: crispEdges;
        }
        </style>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
        <script>
        // Set the dimensions of the canvas / graph
        var margin = {top: 30, right: 20, bottom: 30, left: 50},
        width = 600 - margin.left - margin.right,
        height = 270 - margin.top - margin.bottom;
        // Parse the date / time
        var parseDate = d3.time.format("%d-%b-%y").parse;
        // Set the ranges
        var x = d3.time.scale().range([0, width]);
        var y = d3.scale.linear().range([height, 0]);
        // Define the axes
        var xAxis = d3.svg.axis().scale(x)
        .orient("bottom").ticks(5);
        var yAxis = d3.svg.axis().scale(y)
        .orient("left").ticks(5);
        // Define the line
        var valueline = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.close); });

        // Adds the svg canvas
        var svg = d3.select("body")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");
        // Get the data
        // d3.json("data.json", function(data) {
        // data.forEach(function(d) {
        // d.date = parseDate(d.date);
        // d.close = +d.close;
        // });
        d3.json("data.json", function(error, data) {
        data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;
        });
        // Scale the range of the data
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain([0, d3.max(data, function(d) { return d.close; })]);
        // Add the valueline path.
        svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data));
        // Add the X Axis
        svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
        // Add the Y Axis
        svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
        });
        </script>
    </body>
</html>

用D3实现数据可视化
/*设置CSS*/
正文{font:12px Arial;}
路径{
笔画:钢蓝;
笔画宽度:2;
填充:无;
}
.轴线路径,
.轴线{
填充:无;
笔画:灰色;
笔画宽度:1;
形状渲染:边缘清晰;
}
//设置画布/图形的尺寸
var margin={顶部:30,右侧:20,底部:30,左侧:50},
宽度=600-边距。左侧-边距。右侧,
高度=270-margin.top-margin.bottom;
//解析日期/时间
var parseDate=d3.time.format(“%d-%b-%y”).parse;
//设定范围
var x=d3.time.scale().range([0,width]);
变量y=d3.scale.linear().range([height,0]);
//定义轴
var xAxis=d3.svg.axis().scale(x)
.方向(“底部”)。刻度(5);
var yAxis=d3.svg.axis().scale(y)
.方向(“左”)。勾号(5);
//界定界线
var valueline=d3.svg.line()
.x(函数(d){返回x(d.date);})
.y(函数(d){返回y(d.close);});
//添加svg画布
var svg=d3.选择(“主体”)
.append(“svg”)
.attr(“宽度”,宽度+边距。左侧+边距。右侧)
.attr(“高度”,高度+边距。顶部+边距。底部)
.附加(“g”)
.attr(“转换”,
“翻译(“+margin.left+”,“+margin.top+”);
//获取数据
//d3.json(“data.json”),函数(data){
//data.forEach(函数(d){
//d.date=解析日期(d.date);
//d.close=+d.close;
// });
d3.json(“data.json”),函数(错误,数据){
data.forEach(函数(d){
d、 日期=解析日期(d.date);
d、 close=+d.close;
});
//缩放数据的范围
x、 域(d3.extent(数据,函数(d){返回d.date;}));
y、 域([0,d3.max(数据,函数(d){返回d.close;})];
//添加valueline路径。
追加(“路径”)
.attr(“类”、“行”)
.attr(“d”,valueline(数据));
//添加X轴
svg.append(“g”)
.attr(“类”、“x轴”)
.attr(“变换”、“平移(0)”、“高度+”)
.呼叫(xAxis);
//添加Y轴
svg.append(“g”)
.attr(“类”、“y轴”)
.呼叫(yAxis);
});

由于您使用节点处理与服务器的交互,因此您提供了通过节点指向文件的路径。类似于以下内容

app.get('/templates/data', function(req, res){
    res.sendfile(data.json);
});
然后将文件放在/template/data/data.json路径中

希望这有帮助

app.use(express.static(__dirname + '/data'));

下面一行修复了它!感谢您的输入!

从第一眼看,似乎是d3.json(“data.json”)…找不到该文件,因此抛出了一个未定义的错误。@Alex_B准确地说。我相信express正在劫持应用程序对json文件的调用。该文件存在吗?它是否位于根目录中?是的,该文件存在,我可以加载d3页面,而不需要节点。