如何在Node.js中从mysql显示数据到html div?

时间:2019-01-13 17:50:38

标签: javascript node.js express

我使用express作为nodejs的框架,这是我在member.ejs页面上的ajax代码

function load_member(){
        $.ajax({
          url: '/load_member',
          success: function(r){
            console.log(r);
          }, error: function(){
            console.log('Error!');
          }
        });
      }

这是我的nodejs代码(server.js)

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.set('view engine', 'ejs');

app.get('/load_member', function(req, res){
  var mysql = require('mysql');

  var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: 'db_node',
    port: '/Applications/MAMP/tmp/mysql/mysql.sock'
  });

  con.connect(function(err) {
      if (err) throw err;

      let sql = "SELECT * FROM users";
      con.query(sql, function (err, result) {
          if (err) throw err;

          result.forEach(value => {
            res.json({ data: result });
          });
      });
  });

});

我从终端收到此错误

/Applications/MAMP/htdocs/nodejs/node_modules/mysql/lib/protocol/Parser.js:80
        throw err; // Rethrow non-MySQL errors
        ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/Applications/MAMP/htdocs/nodejs/node_modules/express/lib/response.js:767:10)
    at ServerResponse.json (/Applications/MAMP/htdocs/nodejs/node_modules/express/lib/response.js:264:10)
    at result.forEach.value (/Applications/MAMP/htdocs/nodejs/server.js:46:17)
    at Array.forEach (<anonymous>)
    at Query.<anonymous> (/Applications/MAMP/htdocs/nodejs/server.js:45:18)
    at Query.<anonymous> (/Applications/MAMP/htdocs/nodejs/node_modules/mysql/lib/Connection.js:502:10)
    at Query._callback (/Applications/MAMP/htdocs/nodejs/node_modules/mysql/lib/Connection.js:468:16)
    at Query.Sequence.end (/Applications/MAMP/htdocs/nodejs/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

尝试一下,您不能多次使用res.json ...

您将迭代视图中的值。...

  con.connect(function(err) {
      if (err) throw err;

      let sql = "SELECT * FROM users";
      con.query(sql, function (err, result) {
          if (err) throw err;

            res.json({ data: result });
      });
  });

答案 1 :(得分:0)

Cannot set headers after they are sent表示对于单个请求,您正在尝试发送多个响应。

遍历数据集以在UI中进行打印将需要在客户端而不是服务器上进行。