React-native 没法使用 xhr2-cookies

最近在学习react-native的开发并写了一些demojavascript

由于SDK使用了 xhr2-cookies js库,致使RN没法发送http请求。业务要求在尽可能不更改SKD的状况下适配RN。java

最近通过不断排查发现Node库中有这么一条语句react

var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
复制代码

global下没有 location 致使这条语句直接catch了 请求固然没有发出去。git

因而我想到了两种方式解决这个问题。github

  1. 直接更改编译后的文件
var defaultProtocol = null;
    if (global.location) {
        defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
    }
    else {
      defaultProtocol = 'http:'
    }
复制代码

比较暴力,直接更改了编译后的代码,在判断没有location的时候将默认的 Protocol 配置成 'http:'react-native

由于不想这么暴力,因此我使用了另外一种方法,在RN初始化时向 global 中注入一个 locationcookie

  1. 在初始化前注入 location

由于我同时用到了 crypto 的库, 因此我使用了 react-native-crypto 如何使用能够查看 react-native-crypto学习

在生成的 shim.js 文件中,手动注入了locationspa

config = {
        protocol: '' // 'https'
    }

    global.location = {
        protocol: config.protocol
    };
复制代码

这样请求就成功的被发送并反回了对应的数据。code

新人第一次写文。 若是有哪里写的不对或者不够完善,欢迎各位指正。

相关文章
相关标签/搜索