Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Can';不要让API调用以本机方式响应_Reactjs_Api_React Native - Fatal编程技术网

Reactjs Can';不要让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(() => {

在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调用,它工作得非常好。但是,上面的代码总是显示我的
请求失败


我已经在我的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)
来检查和调试您面临的错误。