npm-got POST请求form传数组被转字符串,如何实现Python requests同款效果?
问题原因
Python的requests库处理application/x-www-form-urlencoded格式表单数据时,遇到数组类型参数会自动拆分为多个同名键值对(如test=hello&test=world),这是该格式处理多值参数的标准方式之一。
而npm的got库默认表单序列化逻辑,会将数组直接转为逗号分隔的字符串,原因是其内置序列化规则默认采用“逗号拼接”方式处理数组,而非生成多值参数。
解决方案
以下两种方法可实现与Python requests完全一致的POST请求效果:
方法1:手动用querystring编码数据
利用Node.js内置的querystring模块,指定数组序列化方式为“重复键名”,手动编码表单数据后传给got:
const got = require('got'); const querystring = require('querystring'); async function sendRequest() { const formData = { test: ['hello', 'world'] }; // 指定arrayFormat为repeat,生成多个同名参数 const encodedBody = querystring.stringify(formData, null, null, { arrayFormat: 'repeat' }); const response = await got.post('https://httpbin.org/post', { body: encodedBody, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); console.log(response.body); } sendRequest();
方法2:配置got的表单序列化选项
若使用got v11及以上版本,可直接通过formOptions配置数组序列化方式:
const got = require('got'); async function sendRequest() { const response = await got.post('https://httpbin.org/post', { form: { test: ['hello', 'world'] }, // 设置arrayFormat为repeat,让got生成多值参数 formOptions: { arrayFormat: 'repeat' } }); console.log(response.body); } sendRequest();
以上两种方式都会生成test=hello&test=world的表单数据,请求后httpbin返回的form字段中,test会以数组["hello", "world"]形式呈现,与Python requests结果完全一致。
内容的提问来源于stack exchange,提问作者Akhil Kothapalli
相关产品推荐
相关产品推荐

