Quiero que el código devuelva una matriz 2d de los resultados. Por ejemplo: clothes = [[1,"name","desc"],[2,"name2","desc2"]] ¿puedes hacer que res envíe una lista o tienes que hacer una lista una vez que la hayas devuelto?
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();Sí, por supuesto.
Consulte la documentación oficial de NodeJS
Ejemplo:
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)); }); }); });Aquí tienes un método de conveniencia para hacer lo anterior:
... con.query(query, function (err, results, fields) { if (err) throw err; var clothes = []; res.json(clothes); }); ...Esta es una buena respuesta sobre cómo hacer esto.
En resumen: se recomienda utilizar el nuevo método fetch() en el lado del cliente.
fetch("http://localhost:3000/post") .then(function(response) { return response.json(); }) .then(function(clothes) { document.getElementById("demo").innerHTML = clothes; });