Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
¿Puedes hacer que el nodo js envíe una matriz, no una cadena?

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();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

Parece que estás usando el framework expresjs

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

Lea la respuesta en el lado del cliente

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; });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!