我想做的是将我的 Node js 数据从我的数据库发送到 Handlebars 模板。但当我将其发送到模板时,它显示为 [object Object]。我不知道为什么它们被读取为 [object Object],即使在请求网页中我的数据正常显示。
我尝试了以下方法:JSON.parsing、JSON.stringify、GSON.parsing 和 JSON.stringify 我的数据来测试会发生什么,但使用这些方法时数据不会显示。
-------SERVER.JS-------------
app.use('/number',function(req, res){ // created an API which gets the MySQL data onto that certain web directory
db.query("SELECT * FROM qnumber",function(error,rows,fields){ //query the data with the function and its parameters
if(value <= rows.length){
value++;
const getNumber = rows[value].qNumberCount;
console.log('array: '+value +' = '+ getNumber);
console.log(getNumber);
res.render('index',{title: 'CIV Queueing System',getNumber});
// res.send(getNumber);
}
else{
console.log('Error in Query!');
console.log(error); //display in the console the specific error
}
});
});
-------index.handlebars-------------
<html>
<head>
<style>
body{background: rebeccapurple;font-family: verdana;color: whitesmoke;padding: 30px;}
h1{font-size: 48px; text-transform: uppercase; letter-spacing: 2px; text-align: center;}
p{font-size: 16px;text-align: center;}
</style>
<h1>Queue Counts</h1><br>
</head>
<body class="text-center">
<script src="/reload/reload.js">
var stringJSON = JSON.stringify({{this}});
var parseJSON = JSON.parse({{this}});
var gsonParse = gson.parse({{this}});
var gsonString = gson.stringify({{this}});
</script>
This: {{this}}<br><br>
stringGSON: {{gsonString}}<br><br>
parseGSON: {{gsonParse}}<br><br>
parseJSON: {{parseJSON}}<br><br>
stringJSON: {{stringJSON}}<br><br>
</body>
</html>
最佳答案
这是因为您直接在 this
上执行所有操作。 JavaScript 中的 this
始终指向一个对象。要获取对象的属性值,您需要指定属性名称。
例如,如果数据库中的数据采用以下格式
{
'foo':'bar',
'fooObj':
{
'innerFoo' : 'innerBar'
}
}
然后,以下查询将给出相关结果:
this.foo
将给出 bar
this.fooObj
将给出 [Object][Object]
this.fooObj.innerFoo
将给出 innerBar
关于html - 我在数据库中的数据被写为 [object object],如 Node JS 中的 Handlebars 模板中所示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565430/