【问题标题】:Sending arrays as JSON using FormData使用 FormData 将数组作为 JSON 发送
【发布时间】:2023-01-30 12:23:43
【问题描述】:

我正在将 FormData 对象发送到端点。电话号码需要格式化为这个 JSON:

"phone": [{"type":"main", "value":"#"}, ...] 否则会被拒绝。在数组中具有两对键和值的单个对象。

const doStuff = () => {
  const formData = new FormData()

  **Have tried below for setting key/value of phone object**

  // Attempt 1
  formData.set('phone', [{ type: 'main', value: '313-555-2121' }])
  // Returns:
  "phone":"[Object Object]"

  // Attempt 2
  formData.set(
    'phone',
    JSON.stringify([{ type: 'main', value: '313-555-2121' }])
  )
  // Returns
  "phone":"[{\"type\":\"main\",\"value\":\"313-555-2121\"}]"

  // Format as single "fields" object and stringify (results in fields: {...stuff}), API needs this.
  const formattedForApi = JSON.stringify({fields: Object.fromEntries(formData.entries())})

  // MAKE POST REQUEST...
}

我上面两次尝试的 API 错误。抱怨需要是“主要”的无效第一个值。我是否遗漏了 stringify 如何影响实际发送的数据?

对于那些想知道的人,API 是 Podio。

【问题讨论】:

    标签: javascript arrays json podio


    【解决方案1】:

    可以在 FormData 中将数组作为 JSON 发送,但需要先将数组编码为字符串,然后再将它们添加到 FormData 对象。这是 JavaScript 中的一个示例:

    const formData = new FormData();
    const array = [1, 2, 3];
    
    // Encode the array into a string
    const encodedArray = JSON.stringify(array);
    
    // Add the encoded array to the FormData object
    formData.append("array", encodedArray);
    
    // Send the FormData object in an HTTP request
    fetch("https://example.com/api", {
        method: "POST",
        body: formData
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
    

    在服务器端,您可以将字符串解码回数组并根据需要使用它。具体实现将取决于您使用的服务器端语言。

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多