繁体   English   中英

如果请求的内容类型为application / json,cakephp如何将有效负载放入$ this-> request-> data?

[英]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-Typeangularjs默认标头是application/json;charset=utf-8 ,如果我将其用作默认标头并使用JSON.stringify我的数据,

CakePHP可以使用它吗?

如果没有,我需要在CakePHP上下文中对我的代码进行哪些更改?

读到告诉我们:

如果您的Content-Type是通常的application/x-www-form-urlencoded ,那么即使您发送了ajax请求, CakePHP也会帮助您将有效负载正确解析为$this->request->data

但是,如果Content-Typeapplication/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM