Gatling JavaScript版POST请求体配置报错,求解决方案
问题解决:Gatling JS POST登录请求报错TypeError: undefined is not a function
你的报错核心原因是使用了错误的请求体构造函数名称:Gatling JavaScript API中,构造字符串请求体的方法是stringBody(首字母小写),而非你代码里的StringBody(大写S)。因为找不到StringBody这个函数,所以触发了undefined is not a function的异常。
另外,你可以用ES6模板字符串简化JSON请求体的写法,避免手动转义双引号,提升代码可读性。
修正后的完整代码如下:
import { atOnceUsers, scenario, simulation } from "@gatling.io/core"; import { http, status, stringBody } from "@gatling.io/http"; export default simulation((setUp) => { const httpProtocol = http.baseUrl('https://example.test.com') .acceptHeader('*/*') .contentTypeHeader('application/json'); const loginAndLogout = scenario('Login and logout') .exec(http('Login').post('/login') // 用模板字符串简化JSON写法,同时使用正确的stringBody .body(stringBody(`{ "username": "testUser", "password": "testPass", "channel": "web" }`)) .check(status().is(200)) ); setUp(loginAndLogout.injectOpen(atOnceUsers(1))).protocols(httpProtocol); });
额外注意事项:
- 确保你的
package.json中@gatling.io/core和@gatling.io/http依赖是最新稳定版本,避免因版本兼容问题出现异常 - 实际测试前,确认登录接口的预期响应状态码是否为200,部分接口可能返回201或其他状态码,需调整
status().is()中的数值 - 如果后续需要动态生成请求体(比如从CSV读取用户数据),可以使用
jsonBody方法直接传入JavaScript对象,无需手动拼接JSON字符串
内容的提问来源于stack exchange,提问作者JohnRambow99
相关产品推荐
相关产品推荐

