简体   繁体   English

如何将查询结果数据传递到Express.js和Mysql中的视图

[英]How to pass query result data to the view in Express.js and Mysql

I am trying to display my query result in my view,but nothing seems to be working as im new to this , I can see the result in the console log but not on my html file 3 我正在尝试在我的视图中显示查询结果,但是似乎没有什么新功能,我可以在控制台日志中看到结果,但不能在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;

and my view is 我的看法是

<!DOCTYPE html>
<html>
 <head>
 <title></title>
 <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <h1>test</h1>
  <p>Welcome to <%= ??????? %> </p>
  </body>
  </html>

Thanks 谢谢

I use EJS as template engine here but you can use any others to. 我在这里使用EJS作为模板引擎,但您也可以使用其他任何工具。

your index.js route file code: 您的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;

and your index.ejs should be like bellow: 并且您的index.ejs应该像下面这样:

 <ul>
  <%for(let i=0; i<myres.length; i++){%>
   <li><%=myres[i].LastName%></li>

  <%}%>
 </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM