使用fetch()从PHP文件获取JSON

时间:2018-10-29 12:14:52

标签: javascript php typescript fetch fetch-api

我有以下data.php文件:

$command = $_REQUEST["command"];
$APIKey = "*******************";

if(!isset ($_REQUEST["command"]))
{
    echo "You didn't provide a valid API command";
}
else
{
  switch($command)
  {
    case "get_token" :
      $dataArr = array("token" => "Bearer " . $APIKey);
      echo json_encode($dataArr, JSON_PRETTY_PRINT);
      break;
    default:
      echo "Incorrect API command";
      break;
   }
}

这意味着我必须在请求中提供特定的命令才能获取数据。如果我使用jQuery的$.getJSON()方法,效果很好:

$.getJSON(
  'php/data.php',
  {
    command: "get_token"
  }, (result) => {
    this.myToken = result.token;
  });

但是我想尝试使用fetch()方法。所以我尝试了这个:

fetch('php/data.php', {
  method: "GET",
  mode: "cors",
  cache: "no-cache",
  credentials: "same-origin",
  headers: {"Content-Type": "application/json; charset=utf-8"},
  body: JSON.stringify({command: "get_token"}),

}).then(result => {
  console.log('fetch', result);
  this.myToken = result.token;
})

在这种情况下,我收到以下错误消息:Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

我尝试将其与POST方法一起使用,仅尝试了body键...似乎没有任何作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

  

在这种情况下,我会收到此错误消息:无法在“窗口”上执行“获取”:使用GET / HEAD方法的请求不能具有正文。

GET请求通常使用查询字符串传递查询数据(而jQuery的getJSON函数将在此处对数据进行编码)。

首先:取下机身:

body: JSON.stringify({command: "get_token"}),

第二:删除声明正文包含JSON

headers: {"Content-Type": "application/json; charset=utf-8"},

第三:将数据编码为查询字符串:

var url = new URL('php/data.php', location);
url.searchParams.append("command", "get_token");
var url_string = url.toString()
console.log(url_string);
fetch(url_string, {/* etc */})