javascript - Fetch API POST 请求响应返回空文本
问题描述
我正在尝试获取我通过 fetch() 发送的发布请求的响应,但结果返回一个空文本。
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
。
您可以通过设置初始化数据的body 选项以包含包含两个参数的表单数据,以'method'
与'map'
一种类似的方式将参数发送到服务器。curl
fetch
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;
}
推荐阅读
- python - Django (fields.E304) - AbstractUser
- router - 如何在 Windows 环境下知道路由器的 ExternalIPAddress
- java - Android - 从通知中打开活动时,getCurrentUser() 返回 null
- html - 当我将链接添加到我的个人资料时,LinkedIn og:image 标签不起作用,但在我发帖时起作用
- mpi - 在 MPI 中达到一定数量的 iovec 后,进程 vm readv 失败
- git - 相同的 git 大小,带和不带 --depth=1
- javascript - 使用 React JS 的“未定义主页”错误
- ssis - BIML 生成的 SSIS 包无法加载,错误为 0x80070057“参数不正确”。CPackage::LoadFromXML 失败
- visual-studio-code - VSCode 上的 Link+tab 快捷方式 Emmet - 我怎样才能让“类型”包含在其中?
- javascript - 在 VPS 上的 Godaddy 中的 CPanel 上运行 Express.JS - 不工作