gpt4 book ai didi

react-native - React Native atob()/btoa() 在没有远程 JS 调试的情况下无法工作

转载 作者:行者123 更新时间:2023-12-03 07:08:18 24 4
gpt4 key购买 nike

我有一个 react native 测试应用程序,当我远程启用调试js时,一切正常。运行后,它在设备(来自 XCode)和模拟器中运行良好:

react-native run ios

问题是,如果我停止远程 js 调试,登录测试将不再起作用。登录逻辑非常简单,我正在获取 api 来测试登录,API 端点通过 https 进行。

我需要改变什么?

更新:此代码与启用 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@example.com'
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)

谢谢。

最佳答案

这就是我修复它的方法。如@chemitaxis建议从 NPM 添加 base-64 模块:

npm i -S base-64

基于此,我提出了几种使用它的方法:

将其导入到您需要的文件中

然后,您可以使用别名导入“encode”和“decode”方法,如下所示:

import {decode as atob, encode as btoa} from 'base-64'

当然,使用别名是可选的。

Polyfill方式

您可以将 atobbtoa 设置为 React Native 上的全局变量。然后,您无需在每个需要的文件上导入它们。您必须添加此代码:

import {decode, encode} from 'base-64'

if (!global.btoa) {
global.btoa = encode;
}

if (!global.atob) {
global.atob = decode;
}

您需要将其放在 index.js 的开头,以便可以在另一个文件使用 atobbtoa 之前加载它>。

我建议您将其复制到一个单独的文件中(假设是base64Polyfill.js),然后将其导入到index.js

关于react-native - React Native atob()/btoa() 在没有远程 JS 调试的情况下无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42829838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com