我有同样的情况,但现在我找到了解决方案。现在我可以把请求的URL没有.json,也可以得到Json数据。
在应用程序控制器中添加将处理您的响应的网络响应。
use Cake \ Network \ Response;
之后,你需要转换Json的输入阵列,所以把这个getJsonInput()
功能在你的AppController
,并在控制器中调用它initialize()
public function getJsonInput() {
$data = file_get_contents("php://input");
$this->data = (isset($data) && $data != '') ? json_decode($data, true) : array();
}
现在,你有$this->data
所有发布数据。所以你可以访问所有的输入。 下面是一个例子:
class UsersController extends AppController {
public function index() {
if ($this->request->is('post')) {
//pr($this->data); //here is your all inputs
$this->message = 'success';
$this->status = true;
}
$this->respond();
}
}
在你的函数结束
现在你需要调用respond()
这是在AppController
public function respond() {
$this->response->type('json'); // this will convert your response to json
$this->response->body([
'status' => $this->status,
'code' => $this->code,
'responseData' => $this->responseData,
'message'=> $this->message,
'errors'=> $this->errors,
]); // Set your response in body
$this->response->send(); // It will send your response
$this->response->stop(); // At the end stop the response
}
定义定义所有变量在AppController
作为
public $status = false;
public $message = '';
public $responseData = array();
public $code = 200;
public $errors = '';
还有一件事要做的是:
在Response.php (/vendor/cakephp/cakephp/src/Network/Response.php)
您需要编辑一行586 echo $content;
至echo json_encode($content);
的_sendContent()
函数。
就是这样。现在您可以将请求网址设置为 domain_name/project_name/users/index
。
尝试使用'Router :: parseExtensions('json');'而不是'Router :: extensions('json');'? – Maraboc
但是,[3-0-migration-guide says](http://book.cakephp.org/3.0/en/appendices/3-0-migration-guide.html)Router :: parseExtensions()已被删除。使用Cake \ Routing \ Router :: extensions()代替。该方法必须在连接路由之前调用。它不会修改现有的路线。 –
@Maraboc任何我不想为我的网址添加扩展名的方法。我想把没有.json扩展名的JSON响应。 –