我正在編寫一個簡單的Web應用程序,該應用程序最初將在登錄頁面時顯示公交路線編號和名稱列表。我用Express和Pug使用MySQL。這裏是服務器端的代碼與來自console.log
前幾個結果一起:如何使用Express和MySQL將SQL查詢結果插入帕格模板?
const express = require('express');
const pug = require('pug');
const bodyParser = require('body-parser');
const path = require('path');
const mysql = require('mysql');
require('dotenv').config();
const app = express();
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
const connection = mysql.createConnection({
host: 'localhost',
user: 'coolio',
password: process.env.DB_PASS,
database: 'routes'
});
app.get('/', function(req, res) {
const routesQuery = "SELECT route, route_name FROM routes";
let routeObj = {};
connection.query(routesQuery, function(err, results) {
if (err) throw err;
for (let i = 0; i < results.length; i++) {
routeObj.route = results[i].route;
routeObj.routeName = results[i].route_name;
console.log(routeObj);
}
});
});
app.listen(3000, function() {
console.log("Listening..");
});
Listening..
{ route: 1, routeName: 'Metric/South Congress' }
{ route: 2, routeName: 'Rosewood' }
{ route: 3, routeName: 'Burnet/Manchaca' }
{ route: 4, routeName: 'Montopolis' }
{ route: 5, routeName: 'Woodrow/South 5th' }
{ route: 6, routeName: 'East 12th' }
到目前爲止,我一直無法弄清楚如何獲得的結果console.log
顯示加載時在頁面上顯示。
把res.render('index', routeObj);
其中console.log
引發關於標題的多個錯誤(Error: Can't set headers after they are sent.
)。但是我無法訪問for循環之外的對象信息;試圖使用routeObj對象呈現我的索引頁面只是顯示一個空白頁面。
這裏是哈巴狗HTML:
html
head
link(rel='stylesheet', type='text/css', href='stylesheets/normalize.css')
link(rel='stylesheet', type='text/css', href='stylesheets/style.css')
body
div.container
div#test
p=routeObj
我似乎更接近時,我包括res.render('index', {routeObj});
的換loop--頁上,然後至少顯示[object Object]
後。
如何獲取我的console.log
中顯示的數據以顯示在我的模板中?