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

使用Playwright发送POST请求报错:请求体缺失问题排查

问题:Playwright request.post() 请求体缺失报错,但Postman可正常请求

使用Playwright的request.post()发送POST请求时,后端返回请求体缺失的错误,但用Postman发送相同参数的请求却能正常获取响应。

报错响应信息

{
  "message" : "Required request body is missing: public org.springframework.http.ResponseEntity<org.scd.model.User>)",
  "errorCode" : "BAD_REQUEST",
  "validationErrors" : [ ]
}

对应的Playwright代码

test("POST Create Post request", async ({ request }) => {
    const raw = JSON.stringify({
        "iban": "DE8123456781234567898",
        "creditor": "",
        "accountHolder": "Max Miller",
        "signatureDate": "2024-02-21T06:21:57.306Z",
        "signatureLocation": "Reynoldston",
    });

    const headers = {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json',           
    };

    const createPostRequestUrl = 'https://test.system.companyname.io/service/v1/872f774d-12d34-67jj4-abcde-4566743450/mandate';

    // 发送请求
    const response = await request.post(createPostRequestUrl, {
        headers: headers,
        body: raw
    });

    // 处理响应
    const responseBody = await response.text();
    console.log(responseBody);
});

请求相关截图

请求相关截图1
请求相关截图2


解决方法

问题核心是Playwright request.post()的参数使用错误:当请求体为JSON格式时,应该用data字段传递,而非body字段。body通常用于非JSON的原始数据(如form-data、纯文本),而data专门用于处理JSON、表单等结构化数据,能确保后端正确识别请求体。

修改后的代码如下:

test("POST Create Post request", async ({ request }) => {
    const payload = {
        "iban": "DE8123456781234567898",
        "creditor": "",
        "accountHolder": "Max Miller",
        "signatureDate": "2024-02-21T06:21:57.306Z",
        "signatureLocation": "Reynoldston",
    };

    const headers = {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json',           
    };

    const createPostRequestUrl = 'https://test.system.companyname.io/service/v1/872f774d-12d34-67jj4-abcde-4566743450/mandate';

    // 使用data字段传递JSON对象,Playwright会自动完成序列化
    const response = await request.post(createPostRequestUrl, {
        headers: headers,
        data: payload
    });

    // 直接解析JSON响应更便捷
    const responseBody = await response.json();
    console.log(responseBody);
});

如果坚持手动序列化JSON字符串,也可以将序列化后的内容传给data字段,效果一致:

const raw = JSON.stringify(payload);
const response = await request.post(createPostRequestUrl, {
    headers: headers,
    data: raw
});

另外可以核对Postman中的请求头是否与代码完全一致,但核心问题已通过替换body为data解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:49:56