Node.js mysql 在 html 站点上显示表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38008406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:27:12  来源:igfitidea点击:

Node.js mysql display table on html site

htmlmysqlnode.js

提问by user3772108

I'm new to node.js and try to display a simple table on a html site. This table should be filled with the data from a mysql select (eg: select * from testtable).

我是 node.js 的新手,并尝试在 html 站点上显示一个简单的表格。该表应填充来自 mysql select 的数据(例如:select * from testtable)。

But I really don't get it how to do it. For someone with PHP background how can I display some sql content in a HTML in nodejs? I know the git mysql nodejs wiki but it didn't help at all since this is only about getting the data and not displaying it on a webpage.

但我真的不明白该怎么做。对于有 PHP 背景的人,如何在 nodejs 的 HTML 中显示一些 sql 内容?我知道 git mysql nodejs wiki 但它根本没有帮助,因为这只是关于获取数据而不是在网页上显示它。

What is the best practice to do something like that in nodeJS? Is there an easy understandable way, or should I stay with PHP? I really like the idea about node.js but the start is like climbing a slippery cliff.

在nodeJS中做这样的事情的最佳实践是什么?有没有简单易懂的方法,还是我应该继续使用 PHP?我真的很喜欢关于 node.js 的想法,但开始就像爬一个滑的悬崖。

I also buyed a book about it, but the book never gets deep into express (because this would be too much information..). So I know about express, pug, serve-static and I was able to serve a simple html. But that's it, no CRUD or REST and I payed 50 for nothing.

我也买了一本关于它的书,但是这本书从来没有深入探讨过快递(因为这将是太多信息......)。所以我知道 express、pug、serve-static 并且我能够提供一个简单的 html。但就是这样,没有 CRUD 或 REST,我白白支付了 50。

EDIT: Do I need to use an API or is maybe using Angular.js the correct way for this?

编辑:我需要使用 API 还是使用 Angular.js 是正确的方法?

EDIT2:

编辑2:

C:\Users\user\node_test\CRUD2>node app.js
module.js:327
throw err;
^

Error: Cannot find module './routes'

at Function.Module._resolveFilename (module.js:325:15)

at Function.Module._load (module.js:276:25)

at Module.require (module.js:353:17)

at require (internal/module.js:12:17)

at Object.<anonymous> (C:\Users\user\node_test\CRUD2\app.js:2:14)
at Module._compile (module.js:409:26)

at Object.Module._extensions..js (module.js:416:10)

at Module.load (module.js:343:32)

at Function.Module._load (module.js:300:12)

at Function.Module.runMain (module.js:441:10)

EDIT3:

编辑3:

C:\Users\user\node_test\CRUD2>node app.js
Express server listening on port 4300
C:\Users\user\node_test\CRUD2\routes\testtable.js:4
var query = connection.query('SELECT * FROM testtable',function(err,rows){
                    ^

TypeError: Cannot read property 'query' of undefined
at C:\Users\user\node_test\CRUD2\routes\testtable.js:4:29
at C:\Users\user\node_test\CRUD2\node_modules\express-myconnection\lib\express-myconnection.js:87:41
at Pool.<anonymous> (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\Pool.js:47:16)
at Handshake.Sequence.end (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\protocol\sequences\Sequence.js:78:24)
at Handshake.ErrorPacket (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\protocol\sequences\Handshake.js:101:8)
at Protocol._parsePacket (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\protocol\Protocol.js:205:24)
at Parser.write (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\protocol\Parser.js:62:12)
at Protocol.write (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\protocol\Protocol.js:37:16)
at Socket.<anonymous> (C:\Users\user\node_test\CRUD2\node_modules\mysql\lib\Connection.js:73:28)
at emitOne (events.js:77:13)

回答by Alessandro

here an example:

这里有一个例子:

app.js

应用程序.js

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');

//Including controller/dao for testtable
var testtable = require('./routes/testtable'); 
var app = express();
var connection  = require('express-myconnection'); 
var mysql = require('mysql');
// all environments
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.use(
    connection(mysql,{

        host: 'localhost',
        user: 'your_user',
        password : 'your_password',
        port : 3306, //port mysql
        database:'dbname'
},'pool')
);
app.get('/testtable', testtable.list);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

routes/testtable.js

路线/testtable.js

exports.list = function(req, res){

  req.getConnection(function(err,connection){   
      var query = connection.query('SELECT * FROM testtable',function(err,rows){
        if(err)
          console.log("Error Selecting : %s ",err );

        res.render('testtable',{page_title:"Test Table",data:rows});
      });
  });
};

views/testtable.ejs

视图/testtable.ejs

<html><body>
<table border="1" cellpadding="7" cellspacing="7">
  <tr>
    <th width="50px">No</th>
    <th>Field 1</th>
    <th>Field 2</th>
    <th>Field 3</th>
  </tr>
  <% if(data.length){ 
    for(var i = 0;i < data.length;i++) { %>
  <tr>
    <td><%=(i+1)%></td>
    <td><%=data[i].field1%></td>
    <td><%=data[i].field2%></td>
    <td><%=data[i].field3%></td>
  </tr>
  <% }
  }else{ %>
  <tr>
    <td colspan="3">No user</td>
  </tr>
<% } %>
</table>
</body></html>

To run this "project" you have to install some node modules, you could create a file called "package.json" in your root directory:

要运行这个“项目”,您必须安装一些节点模块,您可以在根目录中创建一个名为“package.json”的文件:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "ejs": "^1.0.0",
    "express": "3.5.1",
    "express-myconnection": "1.0.4",
    "jade": "*",
    "mysql": "2.2.0"
  }
}

and call "npm install" under your project root.

并在您的项目根目录下调用“npm install”。

I hope it helps you.

我希望它能帮助你。