【问题标题】:Codeception - POST raw JSON stringCodeception - POST 原始 JSON 字符串
【发布时间】:2014-12-27 04:47:18
【问题描述】:

我正在使用 jQuery 发送以下请求

var url = 'http://site.local/api/package/create';
var data = {
  "command": "package",
  "commandParameters": {
    "options": [
      {
        "a": true
      }
    ],
    "parameters": {
      "node_id": 1111,
      "node_name": "Node Name"
    }
  }
}
$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    success: function (a, b, c) {
        // Do something with response
    }
});

也使用 Postman(Chrome 插件)做类似的事情

POST
Content-Type: application/json
Payload:
{
      "command": "package",
      "commandParameters": {
        "options": [
          {
            "a": true
          }
        ],
        "parameters": {
          "node_id": 1111,
          "node_name": "Node Name"
        }
      }
    }

我打算将原始 JSON 字符串发送到我的服务器,而不是让 Jquery 将其转换为发布数据。 我如何在 Codeception 中执行相同的操作,我只是在文档中看不到它,我只看到以下内容..

$I->sendAjaxPostRequest('/updateSettings', array('notifications' => true));

所以我想我想在 Codeception 中发出一个 POST 请求,同时在请求正文中附加 JSON?

【问题讨论】:

    标签: jquery json rest codeception postman


    【解决方案1】:

    codeception/src/Codeception/Module/REST.php 中的 encodeApplicationJson 函数检查标头“Content-Type”和值“application/json”是否存在。

    如果设置了它,它会返回 json_encode($parameters) 这是我想要的字符串,所以我最终会做这样的事情......

        $I->haveHttpHeader('Content-Type', 'application/json');
        $I->sendPOST('api/package/create', [
            'command' => 'package',
            'commandParameters' => [
                'options' => [],
                'arguments' => []
            ]
        ]);
        $I->canSeeResponseCodeIs(200);
        $I->seeResponseIsJson();
    

    关于 sendpostsendajaxpostrequest

    之间区别的一些信息

    http://phptest.club/t/what-is-the-difference-between-sendpost-and-sendajaxpostrequest/212#post_2

    【讨论】:

      【解决方案2】:

      我认为您应该告诉jQuery 不要处理您传递的数据。 试试这个

      $.ajax({
          url: url,
          type: "POST",
          processData: false,
          data: JSON.stringify(data),
          contentType: "application/json",
          success: function (a, b, c) {
              // Do something with response
          }
      });
      

      在php端你可以使用下面的代码来获取原始数据

      $rawdata = file_get_contents('php://input'); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 2018-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        相关资源
        最近更新 更多