使用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
相关产品推荐
相关产品推荐

