Reputation: 191
I use express as framework of nodejs, this is my ajax code on page member.ejs
function load_member(){
$.ajax({
url: '/load_member',
success: function(r){
console.log(r);
}, error: function(){
console.log('Error!');
}
});
}
and this is my nodejs code (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 });
});
});
});
});
I got this error from terminal
/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)
thank you very much for your help.
Upvotes: 0
Views: 441
Reputation: 31005
Try with this, you cannot use res.json multiple times...
You'll iterate on the values in your 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 });
});
});
Upvotes: 2
Reputation: 329
Cannot set headers after they are sent
indicates that for a single request, you are attempting to send multiple responses.
Iterating over your dataset to print it in the UI will need to happen on the client, rather than server.
Upvotes: 0