简体   繁体   中英

Fetch API POST request response returns empty text

I am trying to get the response of a post request I'm sending via fetch() but the result returns an empty text.

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>
?>

I tested the php response with curl in cmd: curl -X POST localhost/game/repository/maps.php -d "method=getcompletiontimes&map=map_1" and it returned "2" as a response.

The curl request to the server is a HTTP POST request with application/x-www-form-urlencoded content type and the data is transmitted similar to how browsers submit an HTML form. This request data contains 'method' and 'map' parameters.

However, in fetch implementation 'method' and 'map' parameters are sent as URL query parameters. This way they are not available in the $_POST global array but $_GET global array.

You can have 'method' and 'map' parameters sent to the server in a similar way as the curl one by setting the body option of the fetch initialization data to contain form data containing both parameters.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM