我正在使用InfinityFree托管我的mysql数据库,并希望将数据从我的React Native按钮按下到服务器端API但这个“AXIOS错误[AxiosError:请求失败,状态代码为400]”错误。请帮帮我
//.js
const insertData = async () => {
const firstName = 'John';
const lastName = 'Doe';
try {
var postData = JSON.stringify({
firstName,
lastName,
});
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
}
};
axios.post('http://mywebsite.great-site.net/insert.php', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
} catch (error) {
console.error('Error inserting data:', error);
}
};
字符串
此外,我已经注意到,错误只显示了每隔一个按钮按下。
//insert.php in infinityfree domain file manager
<?php
$host = "sql213.infinityfree.com";
$username = "if0_00000000";
$password = "password";
$database = "if0_34528777_mydatabase";
$conn = new mysqli($host, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the request is a POST request
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Get the data from the POST request (sent from React Native app)
$Acc_FirstName = $_POST["firstName"];
$Acc_LastName = $_POST["lastName"];
// Prepare the SQL query to insert the data into the database
$sql = "INSERT INTO `user`(`Acc_FirstName`, `Acc_LastName`) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $Acc_FirstName, $Acc_LastName);
// Execute the query and check for success
if ($stmt->execute()) {
// Data inserted successfully
$response["success"] = true;
$response["message"] = "Data inserted successfully";
} else {
// Failed to insert data
$response["success"] = false;
$response["message"] = "Failed to insert data: " . $conn->error;
}
// Close the prepared statement
$stmt->close();
} else {
// Invalid request method
$response["success"] = false;
$response["message3"] = "Invalid request method";
}
// Set the response headers to indicate JSON content type
header(
// "Content-Type: application/json"
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
});
// Send the JSON response back to the React Native app
echo json_encode($response);
// Close the database connection
$conn->close();
?>
型
这是我第一次这样做,所以我从其他帖子中学习,并向chatgpt寻求帮助
1条答案
按热度按时间z8dt9xmd1#
我没有太多的经验,后端或php,但400错误意味着服务器无法处理的请求,由于无效的信息发送的客户端.首先,请确保该API是与 Postman 或尝试更改内容类型为应用程序/json在axios头,
如果API在postman上工作,那么只需从postman中提取代码并使用它
你可以通过按下右侧的</>图标从postman中提取代码,然后从下拉列表中选择axios
x1c 0d1x的数据