php - Api call to post data not working with either fetch or axios
i'm trying to post data for signup request in react. i tried to check whether the data are passed to the api but it was all empty.Here is my php code for signup api.
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$name = isset($_GET['name']) ? $_GET['name'] : '';
$jsonResponse = array();
$con = mysqli_connect("localhost", "root", "", "example");
if(!$con) {
$jsonResponse = array("code" => "601", "message" => "Unexpected Error, Please try again.");
} else {
$phone_len = strlen($username);
if($phone_len != 10 ){
echo($username);
$jsonResponse = array("code" => "605", "message" => "Mobile number is not 10 Digit","username"=>"$username","password"=>"$password");
} else{...}
here is my code for posting code with fetch.
const requestOption ={
method:'POST',
header:{'Content-Type':'application/json'},
body:JSON.stringify({username:phone,name,password})
};
fetch('http://localhost:8080/example/signup.php',requestOption)
.then(res=>res.json())
.then(data=>{console.log(data);JSON.stringify(data)})
.catch(err=>{
console.log(err)
})
i, too, tried using axios to post the data.
axios.post('http://localhost:8080/example/signup.php', {username:phone,name:name,password:password})
.then(res => {
console.log(res)
console.log(res.data)
})
.catch(err => {
console.log(err)
});
Answer
Solution:
You are using a POST request to send data to the php script. That means you should look into the $_POST variable instead of the $_GET
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
Source