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
1 Answer1
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;} Sign up to request clarification or add additional context in comments.
4 Comments
Vishal Vijay
There is no query support in
fetch?Andreas
You can pass them as
body in theoptions object, but you will have to convert them toURLSearchParams (not supported yet) or FormData. See my edit for an example.Vishal Vijay
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 exampleAndreas
Sorry. Looks like I thought
window.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 toPOSTExplore related questions
See similar questions with these tags.

