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

Using fetch() to get JSON from PHP file

我有以下 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 键...似乎没有任何效果。

有什么想法吗?

In this case I'm getting this error message: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

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 */})