2016-07-26 80 views
0

我試圖使用Handlebars來顯示從MySQL查詢返回的一些數據。路線如下所示:在Express/Node.js中呈現MySQL結果:無法分配給只讀屬性'_locals'

var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; 

connection.query(query, function(err, result) { 
    if (err) throw err 

    var data = JSON.stringify(result); 

    console.log(data); 

    res.render('text', data); 
}); 

「數據」看起來正是我想的那樣,與具有三列和正確的值對象的數組。我的車把的相關部分看起來像:

{{#each data}}{{data.col2}}{{/each}} 

,然後當我嘗試加載網頁,我得到以下錯誤(我可以顯示更多,如果它會幫助):

TypeError: Cannot assign to read only property '_locals' of <and then my array of objects followed by a stack trace> 

我認爲我不瞭解有關如何返回MySQL查詢的內容。

回答

1

完全取出JSON.stringify()線,並通過{ result: result }(或只是{ result },如果您有節點(4.x版+現代版))直接向您的res.render()

該行實際上是將數據庫結果轉換爲JSON 字符串。一個JSON 字符串和一個JavaScript對象是不一樣的。通過關閉JSON.stringify(),您可以保留result一個適當的數組(不是包含數組的字符串),它可以在模板中迭代。

而且,你的車把模板需要看起來像:

 
{{#each result}}{{this.col2}}{{/each}} 
+0

好了,我的結果是現在RowDataPacket的無名數組作爲這樣: '[RowDataPacket {col1中:1 RowDataPacket {col1:2,col2:'ipsum',col3:''}, RowDataPacket {col1:3,col2:'dol',col2:'Lorem',col3:''}, 或',col3:''}, RowDataPacket {col1:4,col2:'sit'',col3:','}' 如果我將這個作爲「result」傳遞給handlebars,我該如何循環它? {{每個結果}} {{result.col2}} {{/每個}}不起作用。 – Kramhsiri

1

似乎要傳遞的字符串類型data到模板。

嘗試更換線

res.render('text', data);

res.render('text', result);

+0

@Kramhsiri改爲'res.render('text',{result:result});'然後你的循環將會工作。 – Calvinxiao

相關問題