php - ( 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
谢谢
解决方案
- 您正在使用 http 请求。React Native 需要 https 连接来发送请求。您可以将服务器切换到 https,或阅读此链接以继续使用 http 请求(已弃用)
- 您的请求正文是多余的逗号,请在发送请求之前尝试将其删除。
var Data = {
RollNo: 'RollNo',
StudentName: 'StudentName',
Course: 'Course', // => remove it
};
推荐阅读
- swift - 如何使用 DiskArbitration 或其他框架在 macOS 上获取磁盘类型(SSD、HDD、Optical)
- php - 即使在设置命名空间之后,Laravel 8 中也没有为 laravel 集体定义 Action Controller@store,除非我使用完整路由
- java - 如何检查和使用来自不同方法的输入
- javascript - 将 HTML 表格保存到仅适用于前 102 个元素的数组中
- reactjs - Form.IO 表单生成器样式
- r - 将惩罚函数应用于具有 R 边界的非线性最小二乘估计收敛 - 包 minpack.lm
- php - 使用 echo 定位 PHP 生成的 HTML ID
- c++ - 我对范围和在 C++ 中声明变量有疑问
- swift - 我正在使用 SpriteKit 制作游戏,但我的视图只占据了屏幕上看似安全的区域。如何扩展此视图?
- python - 有没有办法在 python 中创建漂亮的嵌套表?