Reputation: 312
I'm pretty new to Express and Node MySQL and I've just been trying to figure a few things out. I have a .get()
handler in my app.js file and a button that fetches the handler.
When I log the jsonResponse to the console, it shows me only the first entry - but the app.js seems to be sending all the rows (as logged to the cli console):
// client.js
showUsersButton.addEventListener('click', async () => {
fetch('/show-users').then(response => {
return response.json();
}).then(jsonResponse => {
console.log(jsonResponse); // first row of table
contents.innerHTML = jsonResponse; // [object Object]
contents.innerHTML += jsonResponse.name; // name value for first row in table
})
})
That is the event handler for clicks to the button. The below is the relevant `.get()' method to deal with this:
// app.js
app.get('/show-users', (req, res) => {
connection.connect(error => {
if (error) throw error;
console.log('Connected to the database.');
})
let query = connection.query('SELECT * FROM users');
query.on('result', row => {
console.log(row); // logs all entries of the table
res.send(row);
})
})
When the button is clicked, two results are displayed to the CLI console - both entries that are in the table (I've set this up just so I can learn). The jsonResponse object is logged to the browser console and it shows as only the first entry in the table - it can display to the page too.
But it crashes the server with:
Server side JS is running.
The server is listening for requests at port 5000.
Connected to the database.
RowDataPacket { id: 1, name: 'Danny', level: 1 }
RowDataPacket { id: 2, name: 'Chloe', level: 1 }
C:\Users\User\desktop\node-site\node_modules\mysql\lib\protocol\Parser.js:80
throw err; // Rethrow non-MySQL errors
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)... etc etc
Could anyone let me know what I'm doing wrong?
Upvotes: 0
Views: 267
Reputation: 490
You're calling res.send multiple times. The following code is going to run once per result:
query.on('result', row => {
console.log(row); // logs all entries of the table
res.send(row);
})
You can only call res.send once per request, because it ends the stream. I don't know the library you're using, but it'll likely emit an end/done and error events
const results = [];
query.on('result', row => {
console.log(row); // logs all entries of the table
results.push(result)
})
query.on("end", ()=> res.send(results))
query.on("error", ()=> /* res.send(some error) */)
Upvotes: 1