这是我发送http get请求时的node.js代码,每次请求都会从我的应用程序中获得重复的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!");
}
})
});发布于 2017-09-07 21:28:58
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!");
}
})
});https://stackoverflow.com/questions/46067794
复制相似问题