Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch in react native not send the post

Hello I am trying to send post variables to my API and I not getting the post data in the PHP file

This is my react native code:

let data = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        'firstname': 'test',
    }),
}
fetch(GLOBALS.API + '/registerApi.php?key=' + GLOBALS.KEY, data)
.then((response) => response.json())
.then((responseJson) => {
    Alert.alert(
      'Alert Title',
      responseJson.output
    )

})
.catch((error) => {
    console.error(error);
});

It's returning me empty: []

$array = array(
    "output" => json_encode($_POST)
);
$output = json_encode($array);
die($output);

When I use $_REQUEST it's returning me only the key get parameter without the firstname one.

like image 851
gregory Avatar asked Feb 03 '26 07:02

gregory


1 Answers

JSON.stringify did not work for me, try using FormData instead to prepare data for sending. Here is example:

import FormData from 'FormData';

let formData = new FormData();
formData.append('firstname', 'test');

let data = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: formData
}

fetch(api_url, data)
.then(response => response.json())
.then(responseJson => console.log('response:', responseJson))
.catch(error => console.error(error));
like image 74
Aleksandar Popovic Avatar answered Feb 05 '26 22:02

Aleksandar Popovic