问题描述
我必须发送post方法的数据,其中标头content-type设置为“ x-www-form-urlencoded”。
此表单数据也是嵌套对象。 例如
const formData = { name: "hello",email:abc@gmail.com,education: { subject: "engilsh" ... } } }
解决方法
您可以使用querystring
模块。
发布类似于此类Express伪代码的数据:
const querystring = require('querystring');
// ...
router.post(
'https://api/url',querystring.stringify(formData),headers: { 'Content-Type': 'application/x-www-form-urlencoded' },)
//编辑:querystring
模块不适用于嵌套对象。我的错。我也许建议将对象序列化为JSON字符串。
我假设您遇到的问题是收到的数据显示为 education: [object Object]
。
解决此问题的最简单方法是将标题从 x-www-form-urlencoded
更改为 application/json
。这样,键为 education
的对象不会被序列化为 [object Object]
解决此问题的另一种方法(但很笨拙)是序列化数据客户端:
const formData = { name: "hello",email:abc@gmail.com,education: { subject: "engilsh" ... } } }
const formDataSerial = { raw: JSON.stringify(formData) }
// Send to server
然后在服务器上进行另一步解包:
const dataSerial = formData.raw
const data = JSON.parse(dataSerial)
// Yay!