gre*_*ory 2 php post request react-native
您好我正在尝试将post变量发送到我的API,而我没有在PHP文件中获取发布数据
这是我的反应本机代码:
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);
});
Run Code Online (Sandbox Code Playgroud)
它让我空虚: []
$array = array(
"output" => json_encode($_POST)
);
$output = json_encode($array);
die($output);
Run Code Online (Sandbox Code Playgroud)
当我使用$_REQUEST它时,只返回key没有firstname一个参数的get参数.
JSON.stringify对我不起作用,尝试使用FormData来准备发送数据.这是一个例子:
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));
Run Code Online (Sandbox Code Playgroud)
在PHP中,您需要使用
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE)
Run Code Online (Sandbox Code Playgroud)