【发布时间】:2017-05-11 04:44:05
【问题描述】:
我有多个 MySQL 查询结果,其中我呈现第一个并将其余的可调用到单个 EJS 文件 (/data) 作为对象。
我只呈现 first 查询结果 (obj),然后将其余的可调用到 EJS (rsum_total_sales & rsum_count_active)
似乎我第一次加载 EJS 文件时遇到前端 500 错误,例如
rsum_total_sales is not defined
但是当我重新加载浏览器时,我可以让 EJS 正常加载,显示从路由文件中获得的所有需要的结果。
奇怪的是,即使是第一次,在 console.log() 中,我看到所有三个查询结果都已放入我创建的对象中,但是除了第一个直接呈现到的对象之外,它们还不能被 EJS 调用它。
从 EJS 错误中,我可以看到它传递了第一个 connection.query 结果 (obj),它被渲染,但没有传递其余两个 (rsum_total_sales 和 sum_count_active),我只是让它们的对象可调用,直到我重新加载浏览器。
路由文件
var obj = {};
var qsum_total_sales = 'SELECT SUM (total_price) AS s_total_price FROM myrecords';
var qsum_count_active = 'SELECT COUNT (*) AS s_count_active FROM myrecords WHERE NOT status = "canceled" ';
var qdata = 'SELECT * FROM myrecords';
router.get('/data', function(req, res){
connection.query(qdata, function(err, result) {
if(err){
throw err;
} else {
obj = {print: result};
res.render('data', obj);
console.log(obj);
}
});
connection.query(qsum_total_sales, function(err, rows, result) {
if(err){
throw err;
} else {
rsum_total_sales = JSON.parse(rows[0].s_total_price).toFixed(2);
console.log(rsum_total_sales);
//First time prints result but it can't be called to EJS until reloading EJS
}
});
connection.query(qsum_count_active, function(err, rows, result) {
if(err){
throw err;
} else {
rsum_count_active = JSON.parse(rows[0].s_count_active);
console.log(rsum_count_active);
//First time prints result but it can't be called to EJS until reloading EJS
}
});
});
EJS 文件
<tbody>
<% print.forEach(function (datatable) { %>
<tr>
<td><%= datatable.id %></td
<td><%= datatable.full_name %></td>
//rest of loop
</tr>
<% }) %>
</tbody>
// some html code
<h4>Total sales sum is: <%- rsum_total_sales %></h4>
<h4>Total active records are: <%- rsum_count_active %></h4>
前端错误(仅当 EJS 第一次加载到浏览器时)
ReferenceError: C:\NodeJS\CRUD-1\views\data.ejs:39
37| </table>
38| <hr/>
>> 39| <h4>Total sales sum is: <%- rsum_total_sales %></h4>
40| <h4>Total active records are: <%- rsum_count_active %></h4>
rsum_total_sales is not defined
at eval (eval at <anonymous> (C:\NodeJS\CRUD-1\node_modules\ejs\lib\ejs.js:481:12),
<anonymous>:47:17)
at returnedFn (C:\NodeJS\CRUD-1\node_modules\ejs\lib\ejs.js:512:17)
at View.exports.renderFile [as engine] (C:\NodeJS\CRUD- 1\node_modules\ejs\lib\ejs.js:364:31)
at View.render (C:\NodeJS\CRUD-1\node_modules\express\lib\view.js:126:8)
at tryRender (C:\NodeJS\CRUD-1\node_modules\express\lib\application.js:639:10)
at EventEmitter.render (C:\NodeJS\CRUD-1\node_modules\express\lib\application.js:591:3)
at ServerResponse.render (C:\NodeJS\CRUD-1\node_modules\express\lib\response.js:960:7)
at Query._callback (C:\NodeJS\CRUD-1\routes\data.js:36:17)
at Query.Sequence.end (C:\NodeJS\CRUD-1\node_modules\mysql\lib\protocol\sequences\Sequence.js:86:24)
at Query._handleFinalResultPacket (C:\NodeJS\CRUD-1\node_modules\mysql\lib\protocol\sequences\Query.js:144:8)
【问题讨论】:
-
我看不到你在哪里发送
rsum_total_sales和rsum_count_active到前端。