12

How to pass query string withfetch api javascript (https://github.com/github/fetch)?

var url = "http://www.abcd.com";var query = {    a: "test",    b: 2};

Above should be converted tohttp://www.abcd.com?a=test&b=2 when I pass some argument tofetch

Bergi's user avatar
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
askedJan 9, 2016 at 10:52
Vishal Vijay's user avatar

1 Answer1

7
var params = Object.keys(query)                   .map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))                   .join("&")                   .replace(/%20/g, "+");fetch(url + "?" + params);

Or with theoptions object -but this willNOT work withGET andHEAD 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;}
answeredJan 9, 2016 at 11:09
Andreas's user avatar
Sign up to request clarification or add additional context in comments.

4 Comments

There is no query support infetch?
You can pass them asbody in theoptions object, but you will have to convert them toURLSearchParams (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 thoughtwindow.fetch works like jQuery (or any other library) and it will put the params frombody as a querystring if the method isGET. But theStandard (step 31) doesn't allow abody onGET andHEAD requests... So you will have to stick with option one or change the method toPOST

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.