扔错了; ReferenceError:未定义文档

时间:2016-08-08 12:32:49

标签: javascript mysql node.js mysqli

路由器页面

 var express = require('express');
    var router = express.Router();
    var mysql = require('mysql');        

    /* GET home page */
    router.get('/', function(req, res, next) {
        res.render('mysql', {
            title: '',
        });
    });

    var connection = mysql.createConnection({
        host : '',
        user : '',
        password : '',
        database : ''
    });

    connection.connect();        
    connection.query('SELECT hashtag from recipients', function(err, rows, fields) {
      if (!err) {
        console.log(rows);        
            document.getElementById('recipients').innerHTML = rows;        
    }
      else {
        console.log('Error while performing Query.');
    }

    });        
    connection.end();        
    module.exports = router;

观看页面

<html>
<head>

</head>
<body>
<p id='recipients'></p>
<p id='error'></p>

<script>
</script>

</body>

2 个答案:

答案 0 :(得分:0)

// db.js
var connection = mysql.createConnection({
    host : '',
    user : '',
    password : '',
    database : ''
});
connection.connect();
module.exports = connection;

...
// router.js
var db = require('db.js')

router.get('/', function(req, res, next) {
    db.query('SELECT hashtag from recipients', function(err, rows, fields) {
        if (err) {
            return next(err); // or res.send(err.message);

        res.render('mysql.html', {
            title: '',
            recipients : rows   
        });
    }); 
});

module.exports = router;

// mysql.html
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {{recipients}}
</body>
</html>

答案 1 :(得分:-1)

Node.js可能是java脚本,但Node.js与浏览器中使用的常规java脚本之间存在重大差异。 Node.js是一个服务器端平台,就像你用来编写web应用程序或任何其他类型的应用程序的php或python一样,在浏览器上运行的Javascript是客户端用来操纵DOM和许多其他目的。现在有很多事你做错了。

var express = require('express');
var router = express.Router();
var mysql = require('mysql');


/* GET home page */
router.get('/', function(req, res, next) {
  var connection = mysql.createConnection({
    host: '',
    user: '',
    password: '',
    database: ''
  });

  connection.connect();

  connection.query('SELECT hashtag from recipients', function(err, rows, fields) {
    if (!err) {
      console.log(rows);
      //send rows to template engine to render HTML.
      res.render('mysql', {
        rows: rows,
      });
    } else {
      console.log('Error while performing Query.');
    }
  });
  connection.end();
});
<html>

<head>
  <title>something here</title>
</head>

<body>
  <table>
    <tr>some heading</tr>
    <% for(var i=0; i< rows.length; i++) {%>
      <tr>
        <td>
          <!-- row[i].key access some value from object -->
         
          <%= row[i].someKey%>
        </td>
      </tr>
      <% } %>
  </table>
</body>

</html>

现在我假设您使用EJS作为模板引擎。这不是一个工作的例子,只是一个关于如何工作的片段。可能是this教程有助于您尝试做什么。您应该阅读this