2015-06-25 18 views
3

我是一個節點noob,當我介紹我的d3代碼(它本身可以工作)時,我能夠獲得快速/控制檯返回Uncaught TypeError: Cannot read property 'forEach' of undefined(anonymous function) @ json:63event @ d3.js:504respond @ d3.js:1942Node + Express + Swig /將本地json文件傳遞給模板

注意事項 - data.json與模板位於同一目錄中。

我該怎麼辦?在節點內進行d3渲染會更好嗎?如果是這樣,我該如何將它傳遞給swig模板等?

編輯 - 我注意到在開發工具中,json沒有被檢索,但SVG呈現。自從Express被劫持後,我評論了以下內容。

// app.get('/*', function (req, res) { 
// res.send("404 bro"); 
// }); 

現在一個新的錯誤已經上升,這是一個好兆頭!

GET http://localhost:3000/templates/data.json 404 (Not Found) 

再次,對不起,我有點節點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); 
}); 

它回來了

Unhandled rejection TypeError: undefined is not a function 

更新 - 這是我更新的代碼

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> 
+0

從第一次看,似乎d3.json(「data.json」...沒有找到該文件,因此引發了一個未定義的錯誤 –

+0

@Alex_B精確我相信快遞劫持應用程序的調用json文件。 – Mintberry

+0

該文件是否存在?是否位於根目錄? –

回答

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

以下行固定它!感謝您的投入!

1

由於您使用節點與你必須通過節點提供該文件的路徑的服務器來處理你的互動。類似於以下內容。

app.get('/templates/data', function(req, res){ 
    res.sendfile(data.json); 
}); 

然後將該文件放在/template/data/data.json路徑中。

希望這會有所幫助。