Symfony HTTP 响应不包含指定的正文

Symfony HTTP response doesn't contain the specified body

我正在使用以下 javascript 代码来执行 HTTP 请求:

function ready(path) {
    fetch(path, {method : 'put'})
        .then(function (response) {
            console.log(response);
        });
}

此请求在我的服务器上触发了以下功能:

/**
 * @Route("/some/route/{playerName}", name="ready")
 * @param $playerName string
 */
public function toggleReady($playerName) {
    $this->someService->readyUp($playerName);

    $response = new Response(
        'TOGGLE SUCCESS!',
        Response::HTTP_OK,
        array('content-type' => 'text/html'));
    $response->send();
}

在客户端,正在调用 then 并在控制台中打印响应。该响应包含正确的状态代码,但正文为空,bodyUsedfalse。我怎样才能正确地将我想要的 content/body 发送到前端?

我认为你必须这样做:

fetch(path, {method : 'put'})
  .then(response => response.json())
  .then(data => {
    // Here's the content of the body
    console.log(data)
});

"原来我们请求的是body中隐藏的一个可读流,我们需要调用合适的方法将这个可读流转换成我们可以消费的数据。

如果使用 GitHub,我们知道响应是 JSON。我们可以调用response.json来转换数据。

还有其他方法可以处理不同类型的响应。如果您正在请求 XML 文件,那么您应该调用 response.text。如果您要请求图像,请调用 response.blob."

https://css-tricks.com/using-fetch/

由于您的 Content-Type header 是 text/html,您应该使用 returns 的 .text() 方法将响应 body 解析为文本一个承诺:

fetch(path, { method: 'put' })
  .then(response => response.text())
  .then(body => console.log(body))
  .catch(err => console.error(err));

此外,text/plaintext/html

更准确