首页 > 解决方案 > ( ErrorTypeError: Failed to fetch ) 当我尝试从 react native 将值插入我的 Mysql 数据库(在线托管)时出错

问题描述

大家好,当我尝试使用 API 从 React Native CLI 将值插入我的 Mysql 数据库(在线托管)时出现错误。下面找到我的 Insert.js 文件代码和 test.php 文件。请帮助我了解原因我收到此错误,谢谢。

错误->在此处输入图像描述

插入.js 代码

import React, { Component } from "react";
import { View, Text, TextInput, StyleSheet, Button } from "react-native";
export default class StudentInsert extends Component {
  constructor(props) {
    super(props);
    this.state = { RollNo: "", StudentName: "", Course: "" };
  }

  InsertRecord = () => {
    var RollNo = this.state.RollNo;
    var StudentName = this.state.StudentName;
    var Course = this.state.Course;

    if (RollNo.length == 0 || StudentName.length == 0 || Course.length == 0) {
      alert("Please complete all the fields");
    } else {
      var InsertAPIURL = 'https://app.wakilicloud.co.ke/config.php';
      var headers2 = {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      };
      var Data = {
        RollNo: 'RollNo',
        StudentName: 'StudentName',
        Course: 'Course'
      };
      fetch(InsertAPIURL, {
        method: 'POST',
        headers: headers2,
        body: JSON.stringify(Data),
      })
        .then((response) => response.json())
        .then((response) => {
          alert(response[0].Message);
        })
        .catch((error) => {
          alert("Error" + error);
        });
    }
  };

  render() {
    return (
      <View style={styles.ViewStyle}>
        <TextInput
          placeholder={"RollNo"}
          placeholderTextColor={"pink"}
          keyboardType={"number"}
          style={styles.txtStyle}
          onChangeText={(RollNo) => this.setState({ RollNo })}
        />
        <TextInput
          placeholder={"Student Name"}
          placeholderTextColor={"pink"}
          style={styles.txtStyle}
          onChangeText={(StudentName) => this.setState({ StudentName })}
        />
        <TextInput
          placeholder={"Course"}
          placeholderTextColor={"pink"}
          style={styles.txtStyle}
          onChangeText={(Course) => this.setState({ Course })}
        />

        <Button title={"Save"} onPress={this.InsertRecord} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ViewStyle: {
    flex: 1,
    padding: 20,
    marginTop: 10
  },
  txtStyle: {
    borderBottomWidth: 1,
    borderBottomColor: "red",
    marginBottom: 20
  },
});

测试.php

在此处输入图像描述

谢谢

标签: phpmysqlreactjsreact-nativeapi

解决方案


  1. 您正在使用 http 请求。React Native 需要 https 连接来发送请求。您可以将服务器切换到 https,或阅读此链接以继续使用 http 请求(已弃用)
  2. 您的请求正文是多余的逗号,请在发送请求之前尝试将其删除。
var Data = {
    RollNo: 'RollNo',
    StudentName: 'StudentName',
    Course: 'Course', // => remove it
};

推荐阅读