我必须发送标头内容类型设置为“x-www-form-urlencoded”的 post 方法的数据。
这个表单数据也是嵌套对象。 例如
const formData = { name: "hello", email:[email protected], 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]
解决此问题的另一种方法(但很hacky)是序列化数据客户端:
const formData = { name: "hello", email:[email protected], education: { subject: "engilsh" ... } } }
const formDataSerial = { raw: JSON.stringify(formData) }
// Send to server
在服务器上,执行另一个解包步骤:
const dataSerial = formData.raw
const data = JSON.parse(dataSerial)
// Yay!
我知道这篇文章真的很老了,但由于没有人真正回答这个问题,所以我觉得有插话的冲动。基本上递归函数可以做到这一点,因为我有点懒,所以我要求人工智能来做,这是结果
const transformObjectToQueryString = (obj, parentKey = null) => {
let queryString = '';
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
// Construct the full key name
const fullKey = parentKey ? `${parentKey}[${key}]` : key;
if (typeof value === 'object' && value !== null) {
// Recursively process nested objects
queryString += transformObjectToQueryString(value, fullKey);
} else {
// Append key-value pair to the queryString
if (queryString.length > 0) {
queryString += '&';
}
queryString += `${encodeURIComponent(fullKey)}=${encodeURIComponent(value)}`;
}
}
}
return queryString;
};
我没有用大物体对其进行全面测试,但它对于两层深的物体效果非常好。乍一看,我可以看到它没有“紧急停止”,这意味着它在完成处理对象之前不会停止,请小心您的内存使用;)随意添加级别变量并在级别为像任何其他序列化器一样太深了