Fetch in react native不发送帖子

问题描述 投票:2回答:3

您好我正在尝试将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);
});

它让我空虚:[]

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

当我使用$_REQUEST时它只返回key获取参数而没有firstname

php post react-native request
3个回答
4
投票

在PHP中,您需要使用

$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE)

7
投票

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));

1
投票

问题是JSON.stringify。请改用FormData。无需安装,它不是第三方。这个对我有用。

import FormData from 'FormData';

var formData = new FormData();

formData.append('username', 'Andy');

...

{ 
  ... 
  body: formData 
  ... 
}
© www.soinside.com 2019 - 2024. All rights reserved.