简体   繁体   English

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

[英]prevent multiple http request send by using fetch

I'm creating a chrome extension, in which I take input from using prompt and send it to the server using an HTTP request.我正在创建一个 chrome 扩展,在其中我使用提示获取输入,并使用 HTTP 请求将其发送到服务器。 By doing this I'm facing duplication of data, which means the extension is sending multiple requests to the server, which I want to prevent.通过这样做,我面临着数据重复,这意味着扩展正在向服务器发送多个请求,我想防止这种情况发生。 (Note: by taking data from prompt only once it is sending multiple requests of same data) (注意:仅在发送相同数据的多个请求时才从提示中获取数据)

Example code: Front-End:示例代码:前端:

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

Back-End:后端:

app.post("/post", function(req, res) {
    const data = req.body.data;
    dataList.push(data);
    res.status(200).json({
       status: "uploaded"
    });
});

Here, data is one array that stores data taken from the user.这里,data 是一个存储从用户那里获取的数据的数组。

You can limit concurrent requests by a flag您可以通过标志限制并发请求

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM