You need to enable JavaScript to run this app. 使用K6 batch进行负载测试时请求头无法正确发送的问题
优惠活动
大模型
产品
解决方案
定价
更多

使用K6 batch进行负载测试时请求头无法正确发送的问题

解决K6 http.batch中Content-Type和自定义headers不生效的问题

问题的核心是http.batch的请求结构与http.post不同:你不能把headers嵌套在params.headers里,必须将headers作为请求对象的顶层属性直接声明。

当使用http.post时,params.headers是合法写法,但http.batch的每个请求项要求headers独立作为顶层字段,否则K6会忽略自定义headers,并默认将请求的Content-Type设为application/x-www-form-urlencoded,这就是你遇到415错误的原因。

修改后的正确代码如下:

const request1 = {
    method: "POST",
    url: endpointUrl,
    body: requestBody,
    headers: { // 将headers移到顶层,不再嵌套在params中
        "Content-Type": "application/json",
        "custom-header-1": 'value1',
        "custom-header-2": 'value2', 
        "Accept": "application/json"
    }
};

const responses = http.batch([request1])

如果需要设置其他请求参数(如超时、查询参数等),可以保留params字段,但headers仍需单独放在顶层:

const request1 = {
    method: "POST",
    url: endpointUrl,
    body: requestBody,
    headers: {
        "Content-Type": "application/json",
        "custom-header-1": 'value1',
        "custom-header-2": 'value2', 
        "Accept": "application/json"
    },
    params: {
        timeout: 10000 // 示例:设置请求超时时间
        // 其他参数如查询参数等也可放在这里
    }
};

const responses = http.batch([request1])

调整后,自定义headers和Content-Type会被正确传递,服务器将不再返回415媒体类型不支持的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:52:22