Codeception - POST raw JSON string

I am submitting the following request using 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
    }
});

      

Also do something like this with Postman (Chrome plugin)

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

      

I am assuming I am sending a JSON string to my server, instead of having Jquery convert it to post the data. How do I accomplish the same in Codeception, I just don't see it in the documentation, I only see the following.

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

      

So my guess is I want to make a POST request in Codeception, with the JSON attached to the request body?

+3


source to share


2 answers


The encodeApplicationJson function in codeception / src / Codeception / Module / REST.php checks if the "Content-Type" header and the value "application / json" exist.

If set, it returns json_encode ($ parameters), which is a string, which is what I want, so I end up doing something like this ...

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

      



Some info on the difference between sendpost and sendajaxpostrequest

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

+7


source


I think you should say jQuery

not to process the data you transmit. try it

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

      



on the php side you can use the following code to get the raw data

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

      

+2


source







All Articles