我是 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 正在工作,因为它在邮递员中给出了正确的响应。
你忘记在处理之前将其转换为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);
});
};