我试图在我的视图中显示我的查询结果,但似乎没有任何工作,因为我是新手,我可以在控制台日志中看到结果,但不能在我的html文件3上看到
var express = require('express');
var router = express.Router();
var connection = require('../connection');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * FROM articles',function(error,results,fields){
if(error) throw error;
console.log('Data received from Db:\n');
console.log(results);
res.render('index', {data:results,error:null});
});
});
module.exports = router;
我的观点是
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>test</h1>
<p>Welcome to <%= ??????? %> </p>
</body>
</html>
由于
答案 0 :(得分:0)
我在这里使用EJS作为模板引擎,但是您可以使用其他任何人。
您的index.js路由文件代码:
var express = require('express');
const sql = require('mssql');
var router = express.Router();
router.get('/', function(req, res, next) {
var myArr= [];
const request = new sql.Request();
request.query("SELECT * FROM Student", function(err, rows, fields) {
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server
error"});
} else {
// Loop on each row
var lng = rows.recordsets[0].length;
var rc = rows.recordsets[0];
for (var i = 0; i < lng; i++) {
//Create an object to save current row's data
var person = {
'LastName':rc[i].LastName,
'FirstName':rc[i].FirstName
}
// Add object into array
myarr.push(person);
}
// Render index page using array
res.render('index', {"myres": myarr});
}
});
});
module.exports = router;
和您的index.ejs应该像下面这样:
<ul>
<%for(let i=0; i<myres.length; i++){%>
<li><%=myres[i].LastName%></li>
<%}%>
</ul>