Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url query string in fetch api in javascript

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

like image 332
Vishal Vijay Avatar asked Jan 09 '16 10:01

Vishal Vijay


1 Answers

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;
}
like image 52
Andreas Avatar answered Sep 21 '22 10:09

Andreas