Answer the question
In order to leave comments, you need to log in
What packages would you recommend for working with FormData?
Hello.
To send requests to the server, I use the isomorphic-fetch
.
Request can be: GET
and POST
.
With POST
a request, everything is much simpler:
// для body можем использовать, как FormData так и объект ({})
let data = new FormData();
data.append('test', '1');
fetch(path, {
method : 'POST',
headers : {'X-Requested-With' : 'XMLHttpRequest'},
body : data
}).then(response => JSON.parse(response));
GET
request a little more difficult, because. GET
query parameters we have to put in path
(reference). GET
a request (example: list filters). I find it much more convenient to work with form parameters via FormData
:let body = new FormData(document.getElementById("myForm"))
GET
parameters. Answer the question
In order to leave comments, you need to log in
For constructing URLs, it is better to use the URL and URLSearchParams objects:
const url = new URL(path);
const searchParams = new URLSearchParams();
searchParams.append('test', '1');
url.search = searchParams.toString();
fetch(url, {
method : 'GET',
headers : {'X-Requested-With' : 'XMLHttpRequest'}
})
.then(res => res.json())
.then(json => console.log(json));
function formData2searchParams(formData) {
const data = formData.getAll();
const searchParams = new URLSearchParams();
Object.keys(data).forEach(key => searchParams.append(key, data[key]));
return searchParams;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question