【问题标题】:How to display the database content in browser in some format?如何以某种格式在浏览器中显示数据库内容?
【发布时间】:2017-11-03 07:10:17
【问题描述】:

我的 node.js 代码:

http.createServer(function (request, response)
{
    console.log('Creating the http server');
    connection.query('SELECT * FROM navd_compare LIMIT 100', function(err, rows, fields)
   {
        console.log('Connection result error '+err);
        console.log('no of records is '+rows.length);
        response.writeHead(200, { 'Content-Type': 'application/json'});

        response.end(JSON.stringify(rows));
        response.end();
    });

}).listen(8084);

【问题讨论】:

  • 有什么问题?首先不要使用 .end 两次
  • 在哪里/如何定义connection
  • 在浏览器中我得到 JSON 输出,但我希望它在表中。如何检索每行数据 rom 数据库?并将其转换为js对象并在浏览器中打印
  • var http = require('http'); var mysql = 要求('mysql'); var connection = mysql.createConnection({ 主机:'localhost',用户:'root',密码:'tas123',数据库:'navd'});连接
  • 只需使用任何视图引擎,如 ejs 、jade 或手柄栏即可

标签: javascript mysql node.js


【解决方案1】:

如果您想在服务器上编写最少的代码,您可以使用 Express。例如:

var app = express();

app.route('/data')
.get(function(req, res, next) {
  /*your sql query*/
  res.json(result);
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

在此之后,您可以使用 AJAX 在客户端上请求您的路由。这是Fetch API 的示例:

fetch("http://localhost:3000/data").then(r => r.json()).then(data => {
  /* here is your data */
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 2020-07-05
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多