【问题标题】:Can you get node js to send an array not a string你能让node js发送一个数组而不是一个字符串吗
【发布时间】:2022-01-11 15:34:45
【问题描述】:

我希望代码返回结果的二维数组。 例如。 衣服 = [[1,"name","desc"],[2,"name2","desc2"]] 你可以让 res 发送一个列表,还是你必须在你返回它后做一个列表?

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

【问题讨论】:

  • 然后你需要发送一个 JSON,然后在客户端这样处理它。发送:res.json(clothes)。在客户端你需要解析它:JSON.parse(this.response).

标签: javascript node.js response


【解决方案1】:

当然可以。

查看官方NodeJS documentation

例子:

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

您似乎在使用expresjs framework

这里有一个方便的方法来完成上述操作:

...
    con.query(query, function (err, results, fields) {
        if (err) throw err;
        var clothes = [];
        res.json(clothes);
    });
...

在客户端读取响应

This 是关于如何执行此操作的一个很好的答案。

简而言之:建议在客户端使用新的fetch()方法。

fetch("http://localhost:3000/post")
  .then(function(response) {
    return response.json();
  })
  .then(function(clothes) {
    document.getElementById("demo").innerHTML = clothes;
  });

【讨论】:

  • 另外,将来您可能希望使用子元素(如<div class="product"><div class="product-image"></div><div class="product-name"></div></div)呈现一个 html 元素,或者为每个进入香草 js 地狱的产品提供一些东西,因此您可能需要考虑使用 Virtual DOM/组件库/框架,例如 React(我认为最容易设置和学习)、Vue 或 Angular(最难学习)。
猜你喜欢
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2023-03-04
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
相关资源
最近更新 更多