12

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

1 Answer 1

7
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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

There is no query support in fetch?
You can pass them as body in the options object, but you will have to convert them to URLSearchParams (not supported yet) or FormData. See my edit for an example.
TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body @Andreas, I'm getting above error when I tried your example
Sorry. Looks like I thought window.fetch works like jQuery (or any other library) and it will put the params from body as a querystring if the method is GET. But the Standard (step 31) doesn't allow a body on GET and HEAD requests... So you will have to stick with option one or change the method to POST

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.