【问题标题】:How do I fetch data from my back-end (localhost) that's being sent through Fetch API? (PHP, Fetch, React Native, POST request)如何从通过 Fetch API 发送的后端 (localhost) 获取数据? (PHP、Fetch、React Native、POST 请求)
【发布时间】:2020-08-08 18:45:39
【问题描述】:
fetch("http://10.0.2.2:80/NewAdmin/scripts/main/transactions", {
        method:'post',
        headers:{
           "Accept":"application/json", 
           "Content-type":"application/json" 
        },
        // (var) payload looks like this {Header: "Sending", . . .} 
        body:JSON.stringify(payload)
})
.then(res => res.json())
.then(resp => console.log(resp))
.catch(err => console.log(err));

我的 PHP 代码

<?php
$json = json_decode(file_get_contents('php://input'), true);
echo $json;
if($json["Header"] == "Sending"){
    echo json_encode('!WTF');
}else{
    echo json_encode('WTF!'); 
}
?> 

它返回“WTF!”——不是双关语。我错过了什么?

【问题讨论】:

标签: javascript php react-native fetch


【解决方案1】:

试试这个例子,它应该返回“action test”或错误, JS代码:

fetch(ConfigApp.URL + 'transactions.php', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      action: 'action test',
      p: 'addSession',
    }),
  })
    .then(response => response.json())
    .then(responseJson => {
      console.warn(responseJson)
    })
    .catch(function(error) {
      console.warn(Strings.no_result + error.message);
});

PHP 事务v.php:

<?php

 
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the i ncoming RAW post data from JSON.
$decoded = json_decode($content, true);

if(!is_array($decoded)){
    $json_string = json_encode(false);
    print ($json_string);
    die();
}elseif(!isset($decoded["p"])){
    $decoded = $decoded[0];
}

switch ($decoded["p"]) {
    case 'addSession':
            print (json_encode($decoded['action']));
    break;
    default:
        $json_string = json_encode(false);
        print ($json_string);
    break;

}

【讨论】:

  • 我发现我没有包含http://10.0.2.2:80/NewAdmin/scripts/main/transactions/index.php
猜你喜欢
  • 1970-01-01
  • 2016-04-05
  • 2021-02-14
  • 2016-04-06
  • 2023-03-10
  • 2020-11-24
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多