Javascript Symfony HTTP响应不';不包含指定的正文
我使用以下javascript代码执行HTTP请求:Javascript Symfony HTTP响应不';不包含指定的正文,javascript,php,symfony,httpresponse,Javascript,Php,Symfony,Httpresponse,我使用以下javascript代码执行HTTP请求: function ready(path) { fetch(path, {method : 'put'}) .then(function (response) { console.log(response); }); } 此请求在我的服务器上触发以下功能: /** * @Route("/some/route/{playerName}", name="ready") * @pa
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();
}
在客户端,调用
,然后在控制台中打印响应。该响应包含正确的状态代码,但正文为空,且bodyUsed
为false
。如何将所需内容/正文正确发送到前端?我认为您必须这样做:
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。“
请参见,因为您的内容类型
标题是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
更准确。您是否尝试在“method”属性旁边使用“body”属性?还可以尝试以下操作:.then(response=>console.log('Success:',JSON.stringify(response)).catch(error=>console.error('error:',error));据我所知,fetch
的body
属性设置请求的主体,对我得到的响应没有影响。