【问题标题】:Network connection error- react native using expo cli网络连接错误 - 使用 expo cli 进行本机反应
【发布时间】:2021-11-11 16:36:42
【问题描述】:

我正在构建一个 API 和 react-native 应用程序。服务器运行良好(使用 PostMan 测试),但应用程序不调用服务器。当 axios 必须发送 post 请求时,它会阻塞。 我还尝试输入 ip 地址而不是 localhost,但效果不佳。 (这是我的代码)

 const LoginScreen = ({ navigation }) => {
  const [hidePassword, setHidePassword] = useState(true);
  const [message, setMessage] = useState();
  const [messageType, setMessageType] = useState();

  const handleSubmit = (credentials, setSubmitting) => {
    handleMessage(null);
    const url = "http://192.168.1.110:5000/bankrate/login/login";
    axios
      .post(url, credentials)
      .then((res) => {
        const result = res.data;
        const { message, status, data } = result;

        if (status !== "SUCCESS") {
          handleMessage(message, status);
        } else {
          navigation.navigate("HomeScreen", { ...data[0] });
        }
        setSubmitting(false);
      })
      .catch((error) => {
        console.log(error);
        setSubmitting(false);
        handleMessage(
          "An error occurred! Check your network connection and try again!"
        );
      });
  }; 

【问题讨论】:

标签: node.js mongodb react-native axios expo


【解决方案1】:

改用 JavaScript 的 Fetch API:

const handleSubmit = (credentials,setSubmitting) => {
fetch("http://192.168.1.110:5000/bankrate/login/login", {
method: "post",
headers: { "Content-Type": "insert-mime-type-here (see below)" }
body: // whatever you're sending to the server
}}).then((response) => { if (response.status() === 400) { 
// return either response.json() or response.body() or whatever (see below for details) 
else {
return Promise.reject();
}).then((data) => { // do whatever you want to with the data you get from the server }).catch((error) => // promise rejected);

您使用的 MIME 类型是您发送到服务器的任何内容的 MIME 类型。

如果服务器响应一个 JSON 对象,使用 response.json(),那么 data 将是一个 JavaScript 对象。 如果服务器响应其他任何内容,请使用 response.text() 然后数据将是文本。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2020-12-16
    • 1970-01-01
    • 2018-08-28
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2018-08-15
    相关资源
    最近更新 更多