Reactjs Can';不要让API调用以本机方式响应
在react native中设置用于身份验证的API调用有点困难。我使用以下代码:Reactjs Can';不要让API调用以本机方式响应,reactjs,api,react-native,Reactjs,Api,React Native,在react native中设置用于身份验证的API调用有点困难。我使用以下代码: fetch('http://myserver.ngrok.io/auth/login', { method: 'POST', body: { email: 'email@gmail.com', password: 'password', }, }) .then(() => {
fetch('http://myserver.ngrok.io/auth/login', {
method: 'POST',
body: {
email: 'email@gmail.com',
password: 'password',
},
})
.then(() => {
this.props.navigation.navigate('Main');
})
.catch(() => {
this.props.navigation.navigate('Auth');
console.error('Request Failed');
});
我使用的是ngrok,因为一开始,我以为我的android仿真器/设备QR扫描无法连接到计算机的本地主机。我已经在postman中测试了对这个ngrok端点的api调用,它工作得非常好。但是,上面的代码总是显示我的请求失败
我已经在我的android仿真器和我的android手机上通过QR进行了测试。这是语法问题吗?使用fetch发送JSON的正确方法是:
fetch('http://myserver.ngrok.io/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'}
body: JSON.stringify({
email: 'email@gmail.com',
password: 'password',
}),
})
注意JSON.stringify
和标题
此外,即使出现服务器错误,获取也会成功,用户可能输入无效凭据,因此在重定向到main之前,请检查服务器响应:
.then(resp => resp.json())
.then(data => this.props.navigation.navigate(data.correctCredentials ? 'Main' : 'Auth'))
.catch(...)
改用catch(console.log)
来检查和调试您面临的错误。