![](/img/trans.png)
[英]Where do I put $this->request->headers('Content-Type', 'application/json');
[英]if request has content-type as application/json, how does cakephp fit the payload into $this->request->data?
我注意到我的angularjs
需要将头文件设置为以下内容,才能使其与CakePHP
完美配合。
angularApp.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) {
return data;
}
return $.param(data);
}
});
我的CakePHP
是2.4,并使用JsonView
呈现Ajax请求。
我的问题是Content-Type
的angularjs
默认标头是application/json;charset=utf-8
,如果我将其用作默认标头并使用JSON.stringify
我的数据,
CakePHP
可以使用它吗?
如果没有,我需要在CakePHP
上下文中对我的代码进行哪些更改?
读到这告诉我们:
如果您的Content-Type
是通常的application/x-www-form-urlencoded
,那么即使您发送了ajax
请求, CakePHP
也会帮助您将有效负载正确解析为$this->request->data
。
但是,如果Content-Type
为application/json
,则需要使用$this->request->input('json_decode')
基本上,我们假设您的angularjs配置为:
angularApp.config(function ($httpProvider) {
// because you did not explicitly state the Content-Type for POST, the default is application/json
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) {
return data;
}
//return $.param(data);
return JSON.stringify(data);
}
});
那里的信息不完整。
假设您仍在接收数据并将其作为数组进行操作,则需要实际使用$this->request->input('json_decode', true)
。
为了解决问题,请将其另存为AppController或相应控制器上的受保护方法。
protected function _decipher_data() {
$contentType = $this->request->header('Content-Type');
$sendsJson = (strpos($contentType, 'json') !== false);
$sendsUrlEncodedForm = (strpos($contentType, 'x-www-form-urlencoded') !== false);
if ($sendsJson) {
$this->request->useful_data = $this->request->input('json_decode', true);
}
if ($sendsUrlEncodedForm) {
$this->request->useful_data = $this->request->data;
}
return $this->request->useful_data;
}
然后,在适当的操作中,您可以执行
$data = $this->_decipher_data();
$data['User']['id'] = $id;
要么
在beforeFilter中,您可以执行以下操作:
$this->_decipher_data();
然后通过适当的操作执行此操作:
$this->request->useful_data['User']['id'] = $id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.