D
D
d-virt2016-08-14 11:18:50
JavaScript
d-virt, 2016-08-14 11:18:50

What packages would you recommend for working with FormData?

Hello.
To send requests to the server, I use the isomorphic-fetch.
Request can be: GETand POST.
With POSTa 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));

But with the GETrequest a little more difficult, because. GETquery parameters we have to put in path(reference).
I have forms that I want to submit as GETa request (example: list filters). I find it much more convenient to work with form parameters via FormData:
let body = new FormData(document.getElementById("myForm"))

Question: I want to convert from FormData to GETparameters.
Please advise what packages this can be done (unfortunately, I have not found anything completed yet) or are there options to solve this issue without conversion?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
napa3um, 2016-08-14
@d-virt

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

If you want to use exactly FormData, then you can use this function to convert to URLSearchParams:
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 question

Ask a Question

731 491 924 answers to any question