Search code examples
javascriptphpxmlhttprequestcypress

Cypress API request to PHP results in empty $_POST array


I'm trying to automate API tests for my app but I'm hitting a wall.

I can log in to my app in browsers with...

JS:

const request = new XMLHttpRequest();
request.open(method, requestURL);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(parameters);
request.onreadystatechange = function() {
// handle response
};

The password is being encoded with encodeURIComponent prior to the request being sent.

Method is POST.

Resultant URL: http://localhost/myapp/php/apis/users.php?action=log_in&username=myusername&password=8!2fQL%09l

PHP:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = $_POST["action"];

Error message:

<br />
<b>Warning</b>: Undefined array key "action" in <b>C:\xampp\htdocs\myapp\php\apis\users.php</b> on line <b>15</b><br />

Tried API Request $_POST returning empty array but didn't work (php://input is empty).

The other similar questions/answers didn't seem relevant to my issue.

In Postman and Cypress, I'm setting the content-type to application/x-www-form-urlencoded

Cypress code:

it('Log in', () => {
    const pw = encodeURIComponent('8!2fQL%09l');
    cy.request('POST', 'php/apis/users.php?action=log_in&username=myusername&password=' + pw, {
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        }
    }).then((response) => {
        cy.log(response.body);
    });
});

I'm not sure if this matters, but I use query strings for all my API requests, not JSON.

I have the sneaking suspicion that I'm missing something simple and fundamental to be able to achieve my goal... could it be related to the fact that in a browser, when I visit my app, PHP saves a cookie with the session ID and this isn't being done in Postman/Cypress? And the session ID is needed for the $_POST array to be populated?


Solution

  • Seemingly inexplicably, PHP is not setting the $_POST variable with an array of the key/value pairs passed to the server via query string.

    I converted my API calls to pass data as JSON, then used the following code to assign an array of the key/value pairs to $_POST.

    $_POST = get_object_vars(json_decode(file_get_contents("php://input")));