1

我想测试使用 json 数据的宁静控制器。问题是我无法正确发送数据。

这就是我尝试发送数据的方式:

$this->configRequest([
    'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json'
    ],
]);

$this->post('/api/users', "{'username':'Iason','password':'test'}");

debug($this->_response->body());

在我的控制器中,我检查数据:

if (empty($this->request->data)) {
    throw new BadRequestException("No data");
}

检查失败,我得到了错误。

如果我使用 Postman 测试我的 API,一切正常。如果我尝试将数据作为数组发送(如手册http://book.cakephp.org/3.0/en/development/testing.html#controller-integration-testing中所示),我没有任何在控制器中请求数据。我不知道我做错了什么。

4

1 回答 1

3

首先是无效的 JSON 数据,字符串必须用双引号 ( ") 括起来,而不是单引号 ( ')。

值可以是双引号中的字符串、数字、true 或 false 或 null,也可以是对象或数组。这些结构可以嵌套。

字符串是零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义。

http://www.json.org/

application/x-www-form-urlencoded另一个问题是必须通过input选项设置非格式的帖子数据,即非格式化的 POST 正文数据:

$this->configRequest([
    'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json'
    ],
    'input' => '{"username":"Iason","password":"test"}'
]);

$this->post('/api/users');

如果文档有一个例子表明这一点,不会受到伤害。

于 2014-12-07T18:32:48.907 回答