[英]post nested object as formdata using x-www-form-urlencoded content-type
I have to send the data of post method where headers content-type is set to "x-www-form-urlencoded".我必须发送标头内容类型设置为“x-www-form-urlencoded”的 post 方法的数据。
Also this form-data is nested object.此表单数据也是嵌套的 object。 eg例如
const formData = { name: "hello", email:abc@gmail.com, education: { subject: "engilsh"... } } }
You can use the querystring
module.您可以使用querystring
模块。
Post the data like this Express-like pseudocode:像这样发布类似 Express 的伪代码的数据:
const querystring = require('querystring');
// ...
router.post(
'https://api/url',
querystring.stringify(formData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
)
// EDIT: The querystring
module does not work with nested objects. // 编辑: querystring
模块不适用于嵌套对象。 My bad.我的错。 I'd perhaps suggest serializing the object into a JSON string.我可能会建议将 object 序列化为 JSON 字符串。
I assume that the problem you are experiencing is that the data received is shown as education: [object Object]
.我假设您遇到的问题是收到的数据显示为education: [object Object]
。
The easiest way to resolve this problem is to change the header from x-www-form-urlencoded
to application/json
.解决此问题的最简单方法是将 header 从x-www-form-urlencoded
更改为application/json
。 That way the object with the key education
won't be serialised into [object Object]
这样带有密钥education
的 object 就不会被序列化为[object Object]
Another way to resolve this (but hacky) is to serialise the data client side:解决此问题的另一种方法(但很麻烦)是序列化数据客户端:
const formData = { name: "hello", email:abc@gmail.com, education: { subject: "engilsh" ... } } }
const formDataSerial = { raw: JSON.stringify(formData) }
// Send to server
And at the server, do another step of unpacking:并在服务器上,进行另一步解包:
const dataSerial = formData.raw
const data = JSON.parse(dataSerial)
// Yay!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.