ajax fetch api,javascript - Hook all Fetch Api AJAX requests - Stack Overflow

In fact, Fetch Api is supported by native browser and only has one interface: fetch.

The constructor return one Promise, and you can't get the Request、Response when you want to return your Promise to rewrite the fetch's constructor.

The following code doesn't work well.

(function() {

var oldFectch = fetch;

fetch.consotructor = function() {

return new Promise(resolve, reject) {

// your hook code

};

};

})();

So,Does it mean we can't hook all Fetch Api ? NO!

Then, let's do something(edit fetch.js) and rock.

(function(self) {

'use strict';

// comment or delete the following code block

// if (self.fetch) {

// return

// }

var support = {

searchParams: 'URLSearchParams' in self,

iterable: 'Symbol' in self && 'iterator' in Symbol,

// ...

Last, hook every thing as your better!

self.fetch = function(input, init) {

return new Promise(function(resolve, reject) {

var request = new Request(input, init)

var xhr = new XMLHttpRequest()

// Here we go!

// Now we get the XMLHttpRequest Object

// Do what you want!

xhr.onload = function() {

var options = {

status: xhr.status,

statusText: xhr.statusText,

headers: parseHeaders(xhr.getAllResponseHeaders() || '')

}

options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')

var body = 'response' in xhr ? xhr.response : xhr.responseText

resolve(new Response(body, options))

}

// ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值