javascript - 发送前 : function() in fetch API

标签 javascript fetch

我目前正在迁移 ajax 的使用到fetch ,但是我需要 Ajax native 的参数/函数 beforeSend: function() 。我想执行相同的操作,而不需要在 fetch 中实现(例如创建一个新类)

jQuery $.ajax结构:

$.ajax({
    url: '...',
    type: 'post',
    data: {...},
    beforeSend: function() {
        // perform the action..
    },
    success: function(response, status, xhr) {
        // receive response data
    }
});

JavaScript fetch结构:

fetch('...').then((response) => {
    return response.text();
}).then((data) => {
    console.log(data);
});

如何在不需要实现或在获取时创建新类的情况下确定这样的函数。有什么办法或者只有实现吗?由于我的搜索,我只找到了类似 CustomFetch 的实现( Is there a beforesend Javascript promise ) 和其他。

最佳答案

问题已解决!

无需实现和/或创建新的fetch类。仅使用参数作为“函数内的函数”。我希望你能帮助别人!

function ipGetAddress(format) {
  requestFetch = function() {
    // perform the action..
    console.log('** beforeSend request fetch **');
    return fetch.apply(this, arguments);
  }

  requestFetch(`https://api.ipify.org?format=${format}`).then((response) => {
    return response.json();
  }).then((data) => {
    console.log(data.ip);
  });
}

ipGetAddress('json') // return local ip address..

关于javascript - 发送前 : function() in fetch API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66080100/

相关文章:

javascript - 通过 javascript 选择输入复选框时不触发 ng-show

javascript - 管理 React 中的焦点

javascript - 如何在调用后和执行前取消去抖函数?

javascript - 没有内容的异步等待获取API不会继续执行代码。

javascript - 即使 promise 为 200,也无法从刷新 token 生成新的访问 token

javascript - 有没有一种简单的方法可以获取多个请求

javascript - ReactJS类型错误: undefined is not a function (near '...this.state.data.map...' )

javascript - Angular 表单提交不检查表单验证

javascript - 为什么 fetch() 使用 ReadableStream 作为响应正文?

javascript - 将 xhr 或 fetch 请求重定向到新页面的好做法是什么?