0

I am trying to make a login validation form in React and i am using axios to make database calls.

The thing is, i make contact with the server - i get 200 response but the data i post is not there.

This is what i did the first time:

const user = {username: this.state.username, password: this.state.password}
axios.post("http://localhost:80/thinksmart/post_requests/login.php", user)
.then(res => console.log(res))
.catch(err => console.log(err))

Then i tried another approach - where i set up base url :

const api = axios.create({baseURL: 'http://localhost:80'})
    api.post("/thinksmart/post_requests/login.php", user)
    .then(response => {
        console.log(response)
    })
    .catch(error => 
        console.log(error)
    )

and neither of these worked.

In PHP i only do this:

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type'); 
echo json_encode($_POST);

and i get an empty array even though i have data sent (the user data)

1 Answers1

3

You can solve this issue in two ways: 1- PHP code changes: to get the JSON data in the backend you need to execute the following code instead of the $_POST:

$json = file_get_contents('php://input');

2- Javascript code changes: To be able to receive the data in the backend using $_POST you need to send it using FormData more details can be found in the following link: axios post requests using form-data