React Native atob()/ btoa()不能在没有远程JS调试的情况下工作
问题描述:
我有一个测试应用程序,它反应本机,并且当我启用远程调试js时,所有工作都正常。它的工作原理在设备(在Xcode中)和模拟器精细,运行后:React Native atob()/ btoa()不能在没有远程JS调试的情况下工作
react-native run ios
的问题是,如果我停止远程调试JS,登录测试没有工作。这样一登录逻辑很简单,我对api进行提取以测试登录,API端点已通过https。
我需要改变什么?
更新:此代码工作perfetly JS调试远程启用,如果我禁用它,它不再工作。
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react'
import {
AppRegistry,
StyleSheet,
View,
Button,
Alert
} from 'react-native'
export default class MyClass extends Component {
constructor (props) {
super(props)
this.testFetch = this.testFetch.bind(this)
}
async testFetch() {
const email = '[email protected]'
const password = '123456'
try {
const response = await fetch('https://www.example.com/api/auth/login', {
/* eslint no-undef: 0 */
method: 'POST',
headers: {
'Accept': 'application/json' /* eslint quote-props: 0 */,
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(email + ':' + password)
}
})
Alert.alert('Error fail!', 'Fail')
console.log(response)
} catch (error) {
Alert.alert('Error response!', 'Ok')
}
}
render() {
return (
<View style={styles.container}>
<Button
onPress={this.testFetch}
title="Test me!"
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
})
AppRegistry.registerComponent('testingReactNative',() => MyClass)
谢谢。
答
这里你去(https://sketch.expo.io/BktW0xdje)。创建一个单独的组件(例如Base64.js),导入它并准备使用。例如Base64.btoa('123');
// @flow
// Inspired by: https://github.com/davidchambers/Base64.js/blob/master/base64.js
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=';
const Base64 = {
btoa: (input:string = '') => {
let str = input;
let output = '';
for (let block = 0, charCode, i = 0, map = chars;
str.charAt(i | 0) || (map = '=', i % 1);
output += map.charAt(63 & block >> 8 - i % 1 * 8)) {
charCode = str.charCodeAt(i += 3/4);
if (charCode > 0xFF) {
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
},
atob: (input:string = '') => {
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}
};
export default Base64;
+2
谢谢,我刚刚安装了base-64 npm软件包;)https://www.npmjs.com/package/base-64 – chemitaxis
您至少需要在此处添加一些代码。 JS远程调试不太可能导致此错误。 – zvona
嗨@zvona我已经更新了代码的问题......谢谢。 – chemitaxis
好的,我的错误是,“btoa”在未经调试的情况下未定义...但为什么? :) – chemitaxis