【问题标题】:Not Getting anything back after calling Fetch API - React Native调用 Fetch API 后没有得到任何东西 - React Native
【发布时间】:2021-12-14 16:50:23
【问题描述】:

我正在创建一个 React Native,在其中我使用 Fetch 将表单的数据发送到后端 Node.js,一切正常,但在 fetch api 后我无法执行任何操作,即使 console.log 没有运行。

React-Native 代码:

const PostData  = () =>{

        console.log("Posting");


        //Sending Request to Node.js using Fetch API
        fetch("http://192.168.0.107:3000/Adminsignup", {

            //Setting Method
            method:"POST",

            //Setting Headers
            headers:{
                //Setting Content-Type
                "Content-Type" : "application/json"
            },
            //Stringifying the email and password and storing it into body
            body:JSON.stringify({
                name,
                gmail,
                password,
                retype
            })
        }).then(res=>{
            console.log(res);
        }).catch(err=>{
            console.log(err);
        })
    } 

.then.catch 的 fetch api 不起作用。

【问题讨论】:

  • 为什么要混合 async-await 和 promise? .使用异步等待或承诺
  • 好的,我现在正在使用异步,但我仍然没有得到回复
  • 如果您真的完全切换到异步样式,并且不再使用then()anymore,那么请编辑您的帖子以显示新代码。
  • 我尝试过承诺,现在我的代码已更新
  • 在您分享的代码中,您定义了一个函数,但您没有调用它。你真的在任何地方打电话给PostData()吗?

标签: react-native


【解决方案1】:

好的,所以你的前端代码都很好,正如你所说,当你启动 PostData() 函数时你的后端也在工作,检查你是否从后端返回响应。

将此添加到您的注册路线中:

res.status(200).send({result:"Successfully got Response"})

像这样在前端捕获状态:

let final = await fetch("http://192.168.0.107:5000/studentSignup", {
            //Setting Method
            method:"POST",
            //Setting Headers
            headers:{

                //Setting Content-Type
                "Content-Type" : "application/json"
            },
            //Stringifying the email and password and storing it into body
            body:JSON.stringify({name,gmail,password,retype})
        })

        const data = final.status;
        if(data === 200)
        {
            navigation.navigate("Your Route");
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2017-10-08
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多