gpt4 book ai didi

javascript - 如何在nodejs中将mysql中的数据显示到html div?

转载 作者:行者123 更新时间:2023-12-01 01:21:40 25 4
gpt4 key购买 nike

我使用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)

非常感谢您的帮助。

最佳答案

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

您将迭代 View 中的值...

  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 });
});
});

关于javascript - 如何在nodejs中将mysql中的数据显示到html div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com