发布请求未给出正确响应(Android)

问题描述 投票:0回答:1

我是 React Native 博览会的新手,我正在尝试将我的 ReactJS 应用程序转换为 React Native 应用程序。

我正在做一个post登录请求:

 const  submitHandler = async() => {
    await fetch(`${API}/login`, {
      method: "post",
      mode:"no-cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    })
      .then((data) => {
        if (data.error) {
          console.log(data);
        } else  {
          console.log(data.token);
        if(data.token)
        {  AsyncStorage.setItem("jwt", data.token);
          AsyncStorage.setItem("user", JSON.stringify(data.user));
        }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

这是我的输入:

   <TextInput
        value={email}
        onChangeText={setemail}
        placeholder="Email"
      >
</TextInput>
      <TextInput
        value={password}
        onChangeText={setpassword}
        placeholder="Password"
      >
</TextInput>
      <Button title="Login" onPress={()=>submitHandler()}></Button>

对于空字段,它应该给出 {error:"...."} 并且使用正确的字段,它应该给出令牌以及用户的名称和 ID

但是在控制台中,我对于空字段或正确字段都未定义

API 正在工作,因为它在邮递员中给出了正确的响应。

react-native post expo fetch-api
1个回答
0
投票

你忘记在处理之前将其转换为json

const submitHandler = async() => {
    await fetch(`${API}/login`, {
      method: "post",
      mode:"no-cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    })
      .then(res => res.json())
      .then((data) => {
        if (data.error) {
          console.log(data);
        } else  {
          console.log(data.token);
        if(data.token)
        {  AsyncStorage.setItem("jwt", data.token);
          AsyncStorage.setItem("user", JSON.stringify(data.user));
        }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
© www.soinside.com 2019 - 2024. All rights reserved.