【发布时间】:2020-04-15 09:57:54
【问题描述】:
我正在学习 React Native。在这里,我正在制作一个登录注销 API 以使用客户端。 当我在邮递员中尝试时,结果是正确的,但是当我使用 API 时, 我遇到了一个问题:
JSON 解析错误:无法识别的令牌 '
这是我的代码
class AuthScene extends Component {
constructor(props) {
super(props);
this.state = {
username : '',
password : ''
}
}
login= ()=>{
const {username,password} = this.state;
// alert(username);
fetch('https://example.com/auth', {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
})
.then((response) => response.json()).then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(JSON.stringify(responseJson, null, 4))
}).catch((error) => {
alert(JSON.stringify(error));
console.log(error);
// done();
});
}
和
render() {
return (
<Form style={styles.mainForm}>
<Item style={styles.formItems}>
<Input placeholder="Username" style={styles.Input} onChangeText={username => this.setState({username})}/>
</Item>
<Item style={styles.formItems}>
<Input style={styles.Input} secureTextEntry={true} onChangeText={(password) => this.setState({password})}/>
</Item>
<View style={styles.Button}>
<Button block info style={styles.mainBtn} onPress={this.login}>
<Text style={styles.btnText}>Submit</Text>
</Button>
</View>
</Form>
);
}
如何处理这些事情?
我的 json 有问题还是我的代码不正确?
【问题讨论】:
-
我没有看过你的代码,但是这个错误通常表明服务器响应的是 XML(或 HTML)而不是 json。
标签: json reactjs react-native parsing