【问题标题】:Using fetch() to get JSON from PHP file使用 fetch() 从 PHP 文件中获取 JSON
【发布时间】:2019-04-02 08:57:59
【问题描述】:

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

有什么想法吗?

【问题讨论】:

  • 尝试使用 POST 并得到了什么? $command 来自哪里?
  • @JonStirling 使用 POST 我得到了响应,但没有我的令牌。尝试result.json() 并收到以下错误消息:Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0$command 来自请求:$command = $_REQUEST["command"];
  • 请更新问题并显示您的 PHP 脚本的实际代码。现在它确实包含该分配。
  • "Unexpected token - 大多数情况下,这意味着您收到了 HTML 响应,例如错误文档。在网络面板中检查服务器实际响应的内容。
  • json_encode不会在开头放一个

标签: javascript php typescript fetch fetch-api


【解决方案1】:

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

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

首先:移除主体:

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

第二:去掉body包含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 */})

【讨论】:

  • 好的,那种工作。现在我得到了一个 Promise,其中包含包含令牌的 [[PromiseValue]] 对象。但是如何访问这个 Promise 值呢?
  • yourpromise.then(function (data) { console.log(data); });
  • 您可能希望 this.myToken = result.token; 成为 return result.token
  • 这正是我所做的:fetch(url_string, { method: "GET", mode: "cors", cache: "no-cache", credentials: "same-origin", }).then(result => { console.log('fetch', result.json()); }) 但我得到了 Promise 对象。如果我尝试使用result.token,则会收到错误Property 'token' does not exist on type 'Response'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2013-11-14
  • 2020-09-12
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多