You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress发送POST请求至PHP时$_POST数组为空的问题排查

问题:POST请求中$_POST无法获取action参数,自动化测试失败

我正尝试为应用做API自动化测试,但遇到了问题:浏览器中应用登录功能正常,但是用Postman和Cypress发起请求时,PHP后端抛出Undefined array key "action"的警告。

浏览器端正常工作的代码

浏览器中使用的JavaScript请求代码:

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
};

密码会先通过encodeURIComponent编码再发送,请求方法为POST,最终请求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"];
}

报错信息

<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 />

已尝试的方案

试过针对POST请求中$_POST为空数组的常见解决方案,包括检查php://input,但php://input内容为空,其他类似问题的解决方案也未生效。

Cypress测试代码

在Postman和Cypress中均已设置Content-type为application/x-www-form-urlencoded,Cypress的测试代码如下:

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);
    });
});

疑问

我习惯使用查询字符串而非JSON传递API参数,怀疑问题可能与浏览器中PHP会保存会话ID Cookie,而Postman/Cypress未处理会话ID有关?

内容的提问来源于stack exchange,提问作者Zuno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:25:20