【问题标题】:Symfony HTTP response doesn't contain the specified bodySymfony HTTP 响应不包含指定的正文
【发布时间】:2019-01-14 14:10:06
【问题描述】:

我正在使用以下 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。如何正确地将我想要的内容/正文发送到前端?

【问题讨论】:

  • 您是否尝试将“body”属性与“method”属性一起使用? developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • 也试试这个:.then(response => console.log('Success:', JSON.stringify(response))) .catch(error => console.error('Error:',错误));
  • 据我了解,fetchbody 属性设置了请求的主体,对我得到的响应没有影响。

标签: javascript php symfony httpresponse


【解决方案1】:

我认为你必须这样做:

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

“原来,我们请求的内容作为可读流隐藏在正文中。我们需要调用适当的方法将此可读流转换为我们可以消费的数据。

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

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

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

【讨论】:

    【解决方案2】:

    由于您的 Content-Type 标头是 text/html,您应该使用返回承诺的 .text() 方法将响应正文解析为文本:

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

    此外,text/plain 会比 text/html 更准确

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2022-06-25
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2014-11-16
      • 1970-01-01
      相关资源
      最近更新 更多