最近在学习react-native的开发并写了一些demo
因为SDK使用了 xhr2-cookies js库,导致RN无法发送http请求。业务要求在尽量不更改SKD的情况下适配RN。
最近经过不断排查发现Node库中有这么一条语句
var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
复制代码
global下没有 location 导致这条语句直接catch了 请求当然没有发出去。
于是我想到了两种方式解决这个问题。
- 直接更改编译后的文件
var defaultProtocol = null;
if (global.location) {
defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
}
else {
defaultProtocol = 'http:'
}
复制代码
比较暴力,直接更改了编译后的代码,在判断没有location的时候将默认的 Protocol 配置成 'http:'
因为不想这么暴力,所以我使用了另一种方法,在RN初始化时向 global 中注入一个 location
- 在初始化前注入 location
因为我同时用到了 crypto
的库, 所以我使用了 react-native-crypto 如何使用可以查看 react-native-crypto
在生成的 shim.js
文件中,手动注入了location
config = {
protocol: '' // 'https'
}
global.location = {
protocol: config.protocol
};
复制代码
这样请求就成功的被发送并反回了对应的数据。
新人第一次写文。 如果有哪里写的不对或者不够完善,欢迎各位指正。