首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在节点js代码中获取重复的json数据

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

Stack Overflow用户
提问于 2017-09-06 13:57:26
回答 1查看 113关注 0票数 0

这是我发送http get请求时的node.js代码,每次请求都会从我的应用程序中获得重复的json数据。这意味着前一个会话不会过期,如果有新的请求到来,它会发送相同的json数据两次,三次,以此类推。

代码语言:javascript
复制
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!");
    }
  })
});
EN

回答 1

Stack Overflow用户

发布于 2017-09-07 21:28:58

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

代码语言:javascript
复制
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!");
    }
  })
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46067794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档