I want the code to return a 2d array of the results. E.g. clothes = [[1,"name","desc"],[2,"name2","desc2"]] can you make res send a list or do you have to make a list once you have returned it?
app.get('/post', (req, res) => {
con.connect(function(err) {
if (err) throw err;
var query = "SELECT * FROM products"
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
Object.keys(results).forEach(function(key) {
let r = []
var row = results[key];
r.push(row.ID);
r.push(row.name);
r.push(row.link);
r.push(row.imageLink);
r.push(row.type);
r.push(row.colour);
r.push(row.price);
r.push(row.brand);
clothes.push(r);
});
res.send(clothes);
});
});
});
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
clothes = this.response;
document.getElementById("demo").innerHTML = clothes;
};
xhttp.open("GET", "http://localhost:3000/post", true);
xhttp.send();
Yes of course.
Check out the official NodeJS documentation
Example:
app.get('/post', (req, res) => {
con.connect(function(err) {
if (err) throw err;
var query = "SELECT * FROM products"
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
...
// Better set the header so the client knows what to expect; safari requires this
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(clothes));
});
});
});
Here you have a convenience method to do the above:
...
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
res.json(clothes);
});
...
This is a good answer on how to do this.
In short: It is recommended to use the new fetch() method on client side.
fetch("http://localhost:3000/post")
.then(function(response) {
return response.json();
})
.then(function(clothes) {
document.getElementById("demo").innerHTML = clothes;
});