为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼如林 2023-11-02 21:16:52
我正在创建一个 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 是一个数组,存储从用户处获取的数据。
查看完整描述

1 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

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


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

});


查看完整回答
反对 回复 2023-11-02
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信