Cypress API request to PHP results in empty $_POST array - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, April 27, 2023

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?



source https://stackoverflow.com/questions/76113868/cypress-api-request-to-php-results-in-empty-post-array

No comments:

Post a Comment