【问题标题】:How to POST JSON body into new array?如何将 JSON 正文发布到新数组中?
【发布时间】:2022-07-04 15:21:47
【问题描述】:

为了我的生活,我无法解决这个问题......(js noob)

我的 JSON 正文如下所示:

{ "title": "示例 1", “工作”:“设计师A” }

但是 API 希望它在一个数组中,例如:

[{ "title": "示例 1", “工作”:“设计师A” } ]

我怎样才能做到这一点?

  function handleForm(ev) {
    ev.preventDefault(); 
    let jobForm = ev.target;
    let fd = new FormData(jobForm);

    //look at all the contents
    for (let key of fd.keys()) {
      console.log(key, fd.get(key));
    }
    let json = convertFD2JSON(fd);

    //send the request with the formdata
    let url = 'HIDDEN_URL';
    let h = new Headers();
    h.append('Content-Type', 'application/json');

    let req = new Request(url, {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: h,
      body: json,
      method: 'POST',
    });

    fetch(req)
      .then((res) => res.json())
      .then((data) => {
        console.log('Response from server');
        console.log(data);
      })
      .catch(console.warn);
  }

  function convertFD2JSON(formData) {
    let obj = {
    };
    for (let key of formData.keys()) {
      obj[key] = formData.get(key);
    }
    return JSON.stringify(obj);
  }

谢谢!!

【问题讨论】:

    标签: json api post fetch


    【解决方案1】:

    这个其实很简单!我们可以简单地修改以下代码:

    let req = new Request(url, {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: h,
      body: json,
      method: 'POST',
    });
    

    变成这样:

    let req = new Request(url, {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: h,
      body: [json],
      method: 'POST',
    });
    

    不同之处在于上面的代码,我将 JSON 变量封装在 [] 中,将其定义为新数组中的唯一元素。这应该完全按照您的需要工作!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-12
      • 2018-11-11
      • 2022-01-27
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多