如何POST JSON体到新的数组?



无论如何,我都想不出这是怎么回事。

我的JSON的身体是这样的:

{title": "例1";job";设计师"}

但是API希望它在数组中,比如:

[{title": "例1";job";设计师"}]

我怎样才能做到这一点?

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);
}

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

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变量封装在[]中,这将其定义为新数组中的唯一元素。这应该完全按照您的需要工作!

最新更新