簡體   English   中英

獲取 API POST 請求響應返回空文本

[英]Fetch API POST request response returns empty text

我正在嘗試獲取我通過 fetch() 發送的 post 請求的響應,但結果返回一個空文本。

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 請求是一個帶有application/x-www-form-urlencoded內容類型的HTTP POST請求,數據的傳輸類似於瀏覽器提交 HTML 表單的方式。 此請求數據包含'method''map'參數。

但是,在fetch實現中, 'method''map'參數作為 URL 查詢參數發送。 這樣,它們在$_POST全局數組中不可用,但在$_GET全局數組中可用。

您可以通過將fetch初始化數據的body 選項設置為包含包含這兩個參數的表單數據,以與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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM