简体   繁体   English

无法进行 API 调用 React Native

[英]Can't make API calls React Native

I'm having a bit of trouble setting up an API call for authentication in react native.我在 React Native 中设置用于身份验证的 API 调用时遇到了一些麻烦。 I use the following code:我使用以下代码:

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');
        });

I'm using ngrok, because at first, I thought I was having issues with my android emulator/device QR scanning not being able to connect to my computer's localhost.我正在使用 ngrok,因为起初,我以为我的 android 模拟器/设备 QR 扫描出现问题,无法连接到我的计算机的本地主机。 I have tested the api call to this ngrok endpoint in postman, and it has worked perfectly.我已经在 postman 中测试了对这个 ngrok 端点的 api 调用,它运行良好。 However, the above code always gives me my Request Failed .但是,上面的代码总是给我我的Request Failed

I have tested this on both my android emulator and tunneling with my android phone via QR.我已经在我的 android 模拟器和通过 QR 使用我的 android 手机进行隧道测试。 Is this a syntax issue?这是语法问题吗?

The correct way to use fetch to send JSON would be in your case:在您的情况下,使用 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',
  }),
})

Note the JSON.stringify and the header.请注意JSON.stringify和标头。

Also, fetch will be successful even in case of a server error, and the user could enter invalid credentials, so check the server response before redirecting to main:此外,即使在服务器出错的情况下,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM