【问题标题】:My datas in database are written as [object object] as displayed in the handlebar template in Node JS我在数据库中的数据写为 [object object],如 Node JS 中的车把模板中所示
【发布时间】:2019-08-21 19:39:48
【问题描述】:

我想要做的是将我的节点 js 数据从我的数据库发送到车把模板。但是当我将它发送到模板时,它显示为 [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>

【问题讨论】:

    标签: html mysql node.js json express


    【解决方案1】:

    这是因为您直接在this 上执行所有操作。 JavaScript 中的this 总是指向一个对象。要获取对象的属性值,您需要指定属性名称。

    例如,如果您来自 DB 的数据采用格式

    {
     'foo':'bar',
     'fooObj':
     {
       'innerFoo' : 'innerBar'
     }
    }
    

    那么,以下查询将给出相关结果:

    this.foo 会给bar

    this.fooObj 会给[Object][Object]

    this.fooObj.innerFoo 会给innerBar

    【讨论】:

    • 我所做的只是将 This: {{this}}

      更改为 This: {{this.getNumber}}

      。为了指定在 index.handlebars 中显示什么属性。
    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 2015-05-18
    • 2014-01-06
    • 2021-06-11
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2014-01-11
    相关资源
    最近更新 更多