簡體   English   中英

使用 x-www-form-urlencoded content-type 將嵌套的 object 作為 formdata 發布

[英]post nested object as formdata using x-www-form-urlencoded content-type

我必須發送標頭內容類型設置為“x-www-form-urlencoded”的 post 方法的數據。

此表單數據也是嵌套的 object。 例如

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模塊不適用於嵌套對象。 我的錯。 我可能會建議將 object 序列化為 JSON 字符串。

我假設您遇到的問題是收到的數據顯示為education: [object Object]

解決此問題的最簡單方法是將 header 從x-www-form-urlencoded更改為application/json 這樣帶有密鑰education的 object 就不會被序列化為[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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM