当前位置: 代码迷 >> JavaScript >> 将本机 POST 数据反应到 API 不起作用
  详细解决方案

将本机 POST 数据反应到 API 不起作用

热度:31   发布时间:2023-06-13 12:20:51.0

当我使用 React Native 中的 FormData 将数据发布到 php API 时,我收到Notice: Undefined index响应。 但是当我在 php 文件中硬编码参数时,我能够得到结果。

我曾尝试使用 React 文档中的JSON.stringify 我遇到同样的问题。 在服务器端,我尝试了建议的file_get_contents('php://input') ,它只返回 null。

  var data = new FormData();
  data.append({
    latitude: '55555',
    longitude: '9999',
  });

fetch('http://localhost/someapi', {
    method:'POST',
    headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data',
        'Content-length': data.length
    },
    body: data
    })
    .then((response)=>response.text())
    .then((response)=>{
        console.log('  Show response');
        console.log(response);
    })
    .catch((err)=>{
        console.warn(err);
    });

我正在使用response.text()所以我可以显示错误。 否则response.json()会给我Unexpected token <因为它返回 html

这是我的 PHP 服务器代码

 $lat =  $_POST['latitude'];
 $lng =  $_POST['longitude'];
 echo json_encode($lat);

我也试过

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

您正在传递'multipart/form-data'标头,因此您必须将formdata传递给 body 而不是JSON.stringify

 var formData = new FormData();
 formData.append('latitude', 55555);
 formData.append('longitude', 9999);

fetch('http://localhost/someapi', {
    method:'POST',
    headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data'
    },
    body: formData
    })
    .then((response)=>{
        console.log('Response ==>',response);
    })
    .catch((err)=>{
        console.warn(err);
    });

只需省略Fetch API 中的标头对象即可正常工作


 headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data'
    }

解决方案应该是这样的


fetch('http://localhost/someapi', {
    method:'POST',
    body: data
    })
    .then((response)=>response.text())
    .then((response)=>{
        console.log('  Show response');
        console.log(response);
    })
    .catch((err)=>{
        console.warn(err);
    });

  相关解决方案