Node.js request模块同名多参数传递格式异常问题
解决Node.js request模块发送多同名参数格式异常问题
我之前也踩过这个坑!这其实是request模块默认的参数序列化规则在搞鬼,和前端fetch的处理方式不一样导致的。
问题原因
前端用fetch发送city[]=1&city[]=2这种格式时,服务器会自动解析成数组city: [1,2];但request模块默认会把数组参数序列化成带索引的形式,也就是city[][0]=1&city[][1]=2,这就导致服务器端接收的格式异常了。
解决方案
我们可以通过配置request的序列化选项,让它和前端的行为保持一致,具体有两种方式:
方式一:直接配置request的qsStringifyOptions
在发起post请求时,指定qsStringifyOptions的arrayFormat为'repeat',这样就会重复同一个参数名,而不是加索引:
const request = require('request'); request.post({ url: 'http://localhost:3001/api/v2/roles/test', form: { 'city[]': ['1', '2'] // 直接传数组 }, qsStringifyOptions: { arrayFormat: 'repeat' // 关键配置 } }, (error, response, body) => { if (error) { console.error('请求出错:', error); return; } console.log('响应:', body); });
方式二:手动序列化参数
如果需要更灵活的控制,可以用Node内置的querystring模块(或者第三方库qs)手动序列化参数,然后直接传递序列化后的字符串作为请求体:
const request = require('request'); const querystring = require('querystring'); // 手动序列化,指定arrayFormat为repeat const serializedData = querystring.stringify( { 'city[]': ['1', '2'] }, null, null, { arrayFormat: 'repeat' } ); request.post({ url: 'http://localhost:3001/api/v2/roles/test', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: serializedData }, (error, response, body) => { if (error) { console.error('请求出错:', error); return; } console.log('响应:', body); });
这样配置后,服务器端接收到的参数格式就和前端fetch发送的一致了,会解析成city: [1,2]。
内容的提问来源于stack exchange,提问作者Achshar
相关产品推荐
相关产品推荐

