在节点js代码中获取重复的json数据

时间:2017-09-06 05:57:26

标签: mysql node.js

当我发送http get请求时,这是我的node.js代码,从我的app我每次请求时都会重复json数据。这意味着如果新请求到来,之前的会话不会过期,它会发送两次相同的json数据,三次等等。

app.get('/ecom/products', function (req, res) {
  mysql.Connection.query('select * from product', function (err, result) {
    if (err) {

      throw err;
      res.end("error!!!");
    }
    else if (result.length > 0) {
      for (var i = 0; i < result.length; i++) {
        objs.push({
          name: result[i].name,
          description: result[i].description,
          category: result[i].category,
          price: result[i].price,
          quantity: result[i].quantity,
          shipping: result[i].shipping,
          location: result[i].location,
          color: result[i].color,
          link: result[i].link
        });
      }
      res.status(200).send(JSON.stringify(objs));
    }
    else {
      console.log('error occured');
      res.end("error occured!");
    }
  })
});

1 个答案:

答案 0 :(得分:0)

objs数组是全局声明的,它创建一次并且不断地将数据推入其中。您需要为每个新请求声明objs。所以它应该是:

app.get('/ecom/products', function (req, res) {
  mysql.Connection.query('select * from product', function (err, result) {
    if (err) {

      throw err;
      res.end("error!!!");
    }
    else if (result.length > 0) {
     var objs = [];
      for (var i = 0; i < result.length; i++) {
        objs.push({
          name: result[i].name,
          description: result[i].description,
          category: result[i].category,
          price: result[i].price,
          quantity: result[i].quantity,
          shipping: result[i].shipping,
          location: result[i].location,
          color: result[i].color,
          link: result[i].link
        });
      }
      res.status(200).send(JSON.stringify(objs));
    }
    else {
      console.log('error occured');
      res.end("error occured!");
    }
  })
});