【问题标题】:prevent multiple http request send by using fetch防止使用 fetch 发送多个 http 请求
【发布时间】: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


【解决方案1】:

你可以通过一个标志来限制并发请求

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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2019-10-05
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多