[英]Can't make API calls React Native
我在 React Native 中设置用于身份验证的 API 调用时遇到了一些麻烦。 我使用以下代码:
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 调用,它运行良好。 但是,上面的代码总是给我我的Request Failed
。
我已经在我的 android 模拟器和通过 QR 使用我的 android 手机进行隧道测试。 这是语法问题吗?
在您的情况下,使用 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
和标头。
此外,即使在服务器出错的情况下,fetch 也会成功,并且用户可能会输入无效的凭据,因此在重定向到 main 之前检查服务器响应:
.then(resp => resp.json())
.then(data => this.props.navigation.navigate(data.correctCredentials ? 'Main' : 'Auth'))
.catch(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.