获取 API POST 请求响应 returns 空文本
Fetch API POST request response returns empty text
我正在尝试获取通过 fetch() 发送的 post 请求的响应,但结果 returns 为空文本。
JS:
async getTotalCompletionTimes()
{
var res = await fetch("repository/maps.php?method=getcompletiontimes&map="+this.getName(), {method: 'POST'});
const result = await res.text();
return result;
}
PHP
<?php
require_once("user.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
<some code>
else if(isset($_POST["method"]) && $_POST["method"] == "getcompletiontimes" && isset($_POST["map"]))
{
$times = 0;
$users = glob('../users/*', GLOB_ONLYDIR);
foreach($users as $u)
{
if(!file_exists($u."/maps.json")) continue;
$json = json_decode(file_get_contents($u."/maps.json"), true);
foreach($json as $map => $v)
{
if($map == $_POST["map"])
{
$times += $v;
}
}
}
echo $times;
}
<some other code>
?>
我在 cmd 中使用 curl 测试了 php 响应:curl -X POST localhost/game/repository/maps.php -d "method=getcompletiontimes&map=map_1" 并返回“2 "作为回应。
对服务器的 curl 请求是 HTTP POST
请求,内容类型为 application/x-www-form-urlencoded
,数据传输方式类似于浏览器提交 HTML 表单的方式。
此请求数据包含 'method'
和 'map'
参数。
但是,在 fetch
实现中,'method'
和 'map'
参数作为 URL 查询参数发送。这样,它们在 $_POST
全局数组中不可用,但在 $_GET
全局数组中不可用。
您可以通过设置 [=15= 的 body option 以与 curl
类似的方式将 'method'
和 'map'
参数发送到服务器] 初始化数据以包含包含两个参数的表单数据。
async getTotalCompletionTimes()
{
const fd = new FormData();
fd.append("method", "getcompletiontimes");
fd.append("map", this.getName());
const res = await fetch(
"repository/maps.php",
{
method: "POST",
body: fd
});
const result = await res.text();
return result;
}
我正在尝试获取通过 fetch() 发送的 post 请求的响应,但结果 returns 为空文本。
JS:
async getTotalCompletionTimes()
{
var res = await fetch("repository/maps.php?method=getcompletiontimes&map="+this.getName(), {method: 'POST'});
const result = await res.text();
return result;
}
PHP
<?php
require_once("user.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
<some code>
else if(isset($_POST["method"]) && $_POST["method"] == "getcompletiontimes" && isset($_POST["map"]))
{
$times = 0;
$users = glob('../users/*', GLOB_ONLYDIR);
foreach($users as $u)
{
if(!file_exists($u."/maps.json")) continue;
$json = json_decode(file_get_contents($u."/maps.json"), true);
foreach($json as $map => $v)
{
if($map == $_POST["map"])
{
$times += $v;
}
}
}
echo $times;
}
<some other code>
?>
我在 cmd 中使用 curl 测试了 php 响应:curl -X POST localhost/game/repository/maps.php -d "method=getcompletiontimes&map=map_1" 并返回“2 "作为回应。
对服务器的 curl 请求是 HTTP POST
请求,内容类型为 application/x-www-form-urlencoded
,数据传输方式类似于浏览器提交 HTML 表单的方式。
此请求数据包含 'method'
和 'map'
参数。
但是,在 fetch
实现中,'method'
和 'map'
参数作为 URL 查询参数发送。这样,它们在 $_POST
全局数组中不可用,但在 $_GET
全局数组中不可用。
您可以通过设置 [=15= 的 body option 以与 curl
类似的方式将 'method'
和 'map'
参数发送到服务器] 初始化数据以包含包含两个参数的表单数据。
async getTotalCompletionTimes()
{
const fd = new FormData();
fd.append("method", "getcompletiontimes");
fd.append("map", this.getName());
const res = await fetch(
"repository/maps.php",
{
method: "POST",
body: fd
});
const result = await res.text();
return result;
}