防止使用 fetch 发送多个 http 请求

伊山·乔希

我正在创建一个 chrome 扩展,在其中我从 using prompt 获取输入并使用 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 是一个数组,用于存储从用户那里获取的数据。

埃里克斯·克洛廷斯

您可以通过标志限制并发请求

var data = null, 
isLoading = false, // perhaps you need to make this persistent depending on your overall architecture
if (!isLoading) 
{
   data = prompt("Enter your data here");
}
if (data !== null || data !== ''){
isLoading = true;
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");
  isLoading = false
  // note = null;
}).catch((error) => {
  // note = null;
  console.log(error.message);
  isLoading = false
  // alert(error.message);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章