因此,基本上,我有两个JavaScript文件,其中一个是对API进行身份验证的函数,另一个是在模拟器中运行的登录屏幕。尝试进行身份验证时,出现错误:
undefined is not an object (evaluating 'password.toString')
这是登录屏幕文件:
import React, {Component} from 'react';
import {View, Text, TextInput, TouchableOpacity} from 'react-native';
import styles from './login-styles';
import {auth} from '../../fetches/auth';
class LoginBox extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: ''
}
}
render = () => {
return(
<View style={styles.box}>
<View style={styles.header}>
<Text style={{fontSize: 28}}>Bem-vindo ao PostBag v 0.0.2</Text>
</View>
<View styles={styles.app}>
<TextInput style={styles.square}
keyboardType="numeric"
placeholder='Insira sua matrúcla'
onChangeText={(text) => this.setState({username: text})}
value={this.state.username}
/>
<TextInput style={styles.square}
secureTextEntry
placeholder='Insira sua senha'
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
/>
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
<Text style={styles.buttonTxt}>POST</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
export default LoginBox;
这是身份验证功能:
import {Alert} from 'react-native';
export function auth(username, password) {
fetch('https://suap.ifrn.edu.br:443/api/v2/autenticacao/token/',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-csrftoken': 'NDML6yy6HgTUIoypfWMZHMKZ32lgJf5PsNolVnLgewanw5YM4rqwkuvgkyAhEYEA'
},
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
}).then(function(response) {
var json = response.json()
json.then((data) => {
token = data.token
if (typeof token === 'undefined') {
Alert.alert('Não foi possível fazer login')
}
else {
Alert.alert('Login feito com sucesso')
}
})
})
}
如果有人可以帮助我,我将非常感谢。我尝试的所有方法均无效。
答案 0 :(得分:0)
从onPress删除多余的括号。
auth(this.state.username, this.state.password)
答案 1 :(得分:0)
我认为,因为当时password
或username
是null
或undefined
。您可以检查它们是否已定义以及它们是否为字符串,如下所示,
body: JSON.stringify({
username: typeof username === 'string' ? username.toString() : '',
password: typeof password === 'string' ? password.toString() : ''
})
,您的视图应按以下所述进行更改,
onPress={() => auth(this.state.username, this.state.password)}
答案 2 :(得分:0)
更改此
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
到
<TouchableOpacity
style={styles.button}
onPress={() => auth(this.state.username, this.state.password)}
>
此外,每当您使用点运算符(.toString()
)访问对象时,都可以安全地检查对象是否首先存在。
因此,将其转换为一个好主意
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
到
body: JSON.stringify({
username: username && username.toString(),
password: password && password.toString()
})