![](/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.