apifox的post的表单提交的gbk的解决方案
定义全局的方法
项目设置->公共脚本(命名为post的表单的gbk
)
// 定义发送登录接口请求方法
// https://apifox.com/blog/get-request-from-current-endpoint/
POST_FORM_GBK = function () {//获取请求urlconst getRequestUrl = () => {let urlStr = pm.request.url.toString() //全局变量不会解析,会以字符串形式表现(给解析数据) eg: {{TEST_HOST}}/path/to/xxxfvar regex = /\s*{{\s*(.*?)\s*}}\s*/g;var matches = urlStr.match(regex);let content = ""if (matches) {matches.forEach(function (match) {// 去除两边的空格和{{}}content = match.replace(/{{\s*(.*)\s*}}/g, '$1');content = (content + '').replace(/^\s+|\s+$/g, '');});}if (content != '') {let hostStr = pm.globals.get(content)return hostStr + pm.request.url.getPath()} else {return urlStr}}// 获取环境里的 前置 URLconst requestUrlStr = getRequestUrl()let urlencodedArr = pm.request.body['urlencoded']let params = []if (urlencodedArr.hasOwnProperty("members")) {for (let item of urlencodedArr["members"]) {if (!item['disabled']) {params.push({ "key": item["key"], "value": item["value"] })}}}console.log("请求URL:", requestUrlStr)console.log("请求参数:", JSON.stringify(params))// 构造一个 POST x-www-form-urlencoded 格式请求。这里需要改成你们实际登录接口的请求参数。const requestObj = {url: requestUrlStr,method: "POST",header: {"Content-Type": "application/x-www-form-urlencoded;charset=GBK", // 注意:header 需要加上 Content-Type},// body 为 x-www-form-urlencoded 格式body: {mode: "urlencoded", // 此处为 urlencoded// 此处为 urlencodedurlencoded: params,}};return requestObj
}
接口中引入
- post请求,body选择的是
x-www-form-urlencoded
- 前置操作-选择
公共脚本
,选择到post的表单的gbk
- 前置操作-选择-自定义脚本执行(throw不然走apifox的方法,通过全局方法直接请求接口)
// pm.sendrequest 参考文档: https://apifox.com/help/app/scripts/api-references/pm-reference/#pm-sendrequest
pm.sendRequest(POST_FORM_GBK(), function (err, res) {if (err) {console.log("err--",err)} else {console.log("成功--",res)}
});
throw new Error("阻止默认请求");