0

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();
Em Maclean
  • 33
  • 2
  • You need to send a JSON then, and treat it on the client as such. To send: `res.json(clothes)`. And on the client you need to parse it: `JSON.parse(this.response)`. – tromgy Dec 06 '21 at 12:17

1 Answers1

0

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

You seem to be using the expresjs framework

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

Read the response on the client side

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;
  });
MarcRo
  • 2,434
  • 1
  • 9
  • 24