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

k6脚本POST请求自定义Content-Type请求头被替换问题求助

解决k6 POST请求中Content-Type被自动设为application/x-www-form-urlencoded的问题

你的问题根源是调用http.post时参数顺序错误,导致k6没有正确识别你设置的请求体和请求头。

问题代码的错误点

在defaultOperationSubPriority函数中,你调用http.post时只传了URL和params,漏掉了请求体payload:

http.post('http://10.96.59.144:80/SccTestService/v1/requestMirror',  params);

k6的http.post方法签名是http.post(url, body, params),你把params当成了第二个参数(请求体)传入,k6会将这个对象解析为表单格式,自动添加application/x-www-form-urlencoded的Content-Type,覆盖了你在params里的设置。

修正后的代码

只需要调整http.post的参数顺序,把payload作为第二个参数传入,params作为第三个参数:

import http from 'k6/http';

export const payload = JSON.stringify({
    firstField: 'Sample value'
});

export const params = {
   headers: {
      'Content-Type': 'application/json',
    }
};

export const options = {
  discardResponseBodies: false,
  scenarios: {
    defaultOperationPriority: {
      executor: 'constant-vus',
      exec: 'defaultOperationSubPriority',
      startTime: '0s',
      vus: 1,
      duration: '3s',
    },
    configuredOperationPriority: {
      executor: 'constant-vus',
      exec: 'configuredOperationSubPriority',
      startTime: '1s',
      vus: 1,
      duration: '3s',
    },
  },
};

export function defaultOperationSubPriority() {
  // 修正参数顺序:url -> payload -> params
  http.post('http://10.96.59.144:80/SccTestService/v1/requestMirror', payload, params);
}

export function configuredOperationSubPriority() {
//  http.get('http://10.96.59.144:80/SccTestService/v1/id');
}

验证效果

修正后,请求日志中的Content-Type会正确显示为application/json,同时请求体也会携带你定义的JSON数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:32:06