Javascript 在CakePHP3.5中,如何正确地发送正确的HTTP响应
我正在开发一个CakePHP应用程序,为我的ReactJS应用程序建模,但是我在使用Axios从CakePHP应用程序中的一个端点检索动态创建的json时遇到了一个问题 控制器中的操作如下所示:Javascript 在CakePHP3.5中,如何正确地发送正确的HTTP响应,javascript,php,reactjs,cakephp,axios,Javascript,Php,Reactjs,Cakephp,Axios,我正在开发一个CakePHP应用程序,为我的ReactJS应用程序建模,但是我在使用Axios从CakePHP应用程序中的一个端点检索动态创建的json时遇到了一个问题 控制器中的操作如下所示: public function bootstrap($name = null){ $this->autoRender = false; $config = $this->Themes->getJson($name); $config += $this->s
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;
}
axios.get('https://demo.axistaylor.com/ccsllc/themes/json')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
我的React应用程序中的axios请求如下所示:
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;
}
axios.get('https://demo.axistaylor.com/ccsllc/themes/json')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
除了运行react应用程序时打印到控制台的响应之外,其他一切似乎都正常工作
{
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",
…
}
数据返回为空字符串“”。我尝试过改变设置主体和标题的方法,甚至恢复到CakePHP早期版本支持的方法,例如
$this->response->header(…)->body(…)
,结果是一样的。axios请求中列出的端点是公共的,因此您可以自己测试它<代码>https://demo.axistaylor.com/ccsllc/themes/json问题在于初始的$this->response在CakePHP 3.5+中是不可变的,必须在这样一个语句中使用header和body重新分配
$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);
有关信息,请查看ndm提供的问题的答案问题仍然存在,但感谢您的帮助。我不知道$this->响应是部分不变的。我已经更改了我的代码以适应3.5的新要求抱歉,它起作用了。在测试之前,我已将更改提交到服务器。谢谢。