【发布时间】:2021-03-22 16:57:53
【问题描述】:
我正在创建一个 chrome 扩展程序,在其中我使用提示符获取输入并使用 HTTP 请求将其发送到服务器。通过这样做,我面临着数据重复,这意味着扩展正在向服务器发送多个请求,我想防止这种情况发生。 (注意:只有在发送相同数据的多个请求时才从提示中获取数据)
示例代码: 前端:
var data = prompt("Enter your data here");
if (data !== null || data !== ''){
fetch('http://localhost:3000/post', {
method: 'POST',
body: JSON.stringify({
data: data
}),
headers: {
'Content-Type': 'application/json',
}
}).then((res) => {
console.log("wait for whole req");
return res.json();
}).then((resData) => {
console.log(resData);
console.log("req send successfully");
// note = null;
}).catch((error) => {
// note = null;
console.log(error.message);
// alert(error.message);
});
后端:
app.post("/post", function(req, res) {
const data = req.body.data;
dataList.push(data);
res.status(200).json({
status: "uploaded"
});
});
在这里,data 是一个数组,用于存储从用户那里获取的数据。
【问题讨论】:
-
多次请求是什么原因?用户输入?
-
是的,用户输入可能是那个问题,也许它正在创建多个线程。我不知道
标签: javascript jquery node.js dom fetch