[英]How do you properly send a proper HTTP Response in CakePHP 3.5
I am developing an CakePHP app that the Models for my ReactJS application, but I have run into a problem using Axios to retrieve a dynamically created json from one of the endpoints in the CakePHP application. 我正在开发一个ReactPHP应用程序模型的CakePHP应用程序,但是使用Axios从CakePHP应用程序中的一个端点检索动态创建的json时遇到了问题。
The action in the controller looks like this: 控制器中的操作如下所示:
public function bootstrap($name = null){
$this->autoRender = false;
$config = $this->Themes->getJson($name);
$config += $this->systemVars();
$output = json_encode($config);
$this->response
->withHeader('Access-Control-Allow-Origin','*')
->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
->withHeader('Access-Control-Max-Age','8600')
->withType('application/json')
->withStringBody($output);
return $this->response;
}
and the axios request in my React app looks like this: 我的React应用程序中的axios请求看起来像这样:
axios.get('https://demo.axistaylor.com/ccsllc/themes/json')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Everything seems to work fine except this the response that is printed to the console when I run the react app. 除了运行响应应用程序时打印到控制台的响应之外,其他一切似乎都正常运行。
{
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…},
timeout: 0, xsrfCookieName: "XSRF-TOKEN", …},
data:"",
headers:{pragma: "no-cache", content-type: "text/html; charset=UTF-8",
cache-control: "no-store, no-cache, must-revalidate", expires: "Thu, 19 Nov 1981 08:52:00 GMT"},
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …},
status: 200,
statusText: "OK",
…
}
The data comeback as an empty string "". 数据以空字符串“”的形式返回。 I have tried changing the method of setting the body and headers, even reverting to the methods supported by prior versions of CakePHP, eg.
我尝试过更改设置正文和标题的方法,甚至恢复到CakePHP早期版本支持的方法。
$this->response->header(…)->body(…)
, and the results are the same. $this->response->header(…)->body(…)
,结果相同。 The endpoint listed in the axios request is public so you can test it yourself. axios请求中列出的端点是公共的,因此您可以自己对其进行测试。
https://demo.axistaylor.com/ccsllc/themes/json
The problem was the initial $this->response
is immutable in CakePHP 3.5+, and has to be reassigned with header and body in one statement like this. 问题是最初的
$this->response
在CakePHP 3.5+中是不可变的,必须在一个这样的语句中用标头和正文重新分配它。
$this->response = $this->response
->withHeader('Access-Control-Allow-Origin','*')
->withHeader('Access-Control-Allow-Methods',['GET', 'POST'])
->withHeader('Access-Control-Max-Age','8600')
->withType('application/json')
->withStringBody($output);
for information look as the answer to the question here provided by ndm 有关信息,请作为ndm 在此处提供的问题的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.