前言:前一篇 React Native打造自己的fetch(一)我们已经通过源码带大家走了一遍fetch,感觉吧也不是那么有难度,总结起来就是:
- rn端通过fetch传递url跟一些参数(header、body)
- 对传入的url跟参数做一系列的封装,封装成
var request = new Request(input, init)
然后通过request对象把请求需要的设置给XMLHttpRequest对象。
3.通过XMLHttpRequest对象调取native的网络请求方法
4. native网络请求完毕后发通知给rn端
public static void onDataReceived(RCTDeviceEventEmitter eventEmitter, int requestId, String data) {
WritableArray args = Arguments.createArray();
args.pushInt(requestId);
args.pushString(data);
eventEmitter.emit("didReceiveNetworkData", args);
}
5、rn端接收到通知回调onload方法,返回结果。
如果还有不懂的小伙伴可以看我上一片文章。
我们去copy一份fetch的源码然后放入我们自己的工程中,我们取名叫xxxFetch.js,小伙伴自己取名字哈。
xxx/node_modules/whatwg-fetch
(function (self) {
'use strict';
//这里换成我们的ocjFetch
if (self.ocjFetch) {
return
}
......
self.Headers = Headers
self.Request = Request
self.Response = Response
self.ocjFetch = function (input, init, xhrSelf) {
return new Promise(function (resolve, reject) {
var request = new Request(input, init)
var xhr = xhrSelf || new XMLHttpRequest()
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))
}
xhr.onerror = function () {
reject(new TypeError('Network request failed'))
}
xhr.ontimeout = function () {
reject(new TypeError('Network request failed'))
}
xhr.open(request.method, request.url, true)
if (request.credentials === 'include') {
xhr.withCredentials = true
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob'
}
request.headers.fo