How to pass query string with fetch
api javascript (https://github.com/github/fetch)?
var url = "http://www.abcd.com";
var query = {
a: "test",
b: 2
};
Above should be converted to http://www.abcd.com?a=test&b=2
when I pass some argument to fetch
var params = Object.keys(query)
.map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))
.join("&")
.replace(/%20/g, "+");
fetch(url + "?" + params);
Or with the options
object - but this will NOT work with GET
and HEAD
method:
fetch(url, {
method: "POST",
body: convertObjectToFormData(query)
}).then(...);
function convertObjectToFormData(obj) {
var formData = new FormData();
for (var key in obj) {
formData.append(key, obj[key]);
}
return formData;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With