3

I want to use fetch() to query an API endpoint which powers my search page. It returns a list of search results in JSON format.

I also want to pass to the API the current query submitted by the user. The old implementation used jquery and getJSON. Looking at the docs for getJSON, it says that I can pass in a data variable:

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

Looking at the docs for fetch, I'm not sure how to pass in data as part of my request. So my question is, how do I pass in a string that will be sent to the server along with my request?

EDIT: I think I can append the query to the request URL, like "/search/?q=Something" and send that. Does anyone have a better way?

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
a53-416
  • 3,585
  • 6
  • 34
  • 44
  • isn't fetch only build to fetch fixed informations? in the docs i can't find anything to send parameters with fetch. there is get post getJSON ajax and much more with parameters – mtizziani Feb 19 '17 at 17:22
  • What if you don't want the data to be in the request - merely if you want to have the variable exist when responding to the result? – rjurney May 27 '20 at 22:32

2 Answers2

5

If you look at the Body section of the documentation on fetch, it lists several types of values you can use to specify the data sent in your request.

Example using FormData:

var fd = new FormData();
fd.append('q', 'Something');

fetch('/search', {
  method : "POST",
  body : fd
})
.then(...)

Note that you can't use the body option on GET or HEAD requests (which it seems you may be doing in your case). In that situation, you can build up the parameters using URLSearchParams:

var params = new URLSearchParams();
params.append('q', 'Something');

fetch('/search/?' + params.toString(), {
    method: 'GET'
})
.then(...);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Plain `javascript` object does not appear to be tested or expected at `body` https://github.com/w3c/web-platform-tests/blob/master/fetch/api/request/request-idl.html, https://github.com/w3c/web-platform-tests/blob/master/fetch/api/basic/request-upload.js – guest271314 Feb 19 '17 at 18:07
  • 1
    @guest271314 If I call `fetch('/save', { method : "POST", body : { data : 5 } })` in my Chrome console, the request is sent with an empty body and `Content-Length` 0. – JLRishe Feb 19 '17 at 18:08
  • Yes, `javascript` object should be passed to `JSON.stringify()`, see also http://stackoverflow.com/questions/40939857/fetch-with-readablestream – guest271314 Feb 19 '17 at 18:10
0

You can pass as below

 fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})
Jagajit Prusty
  • 2,070
  • 2
  • 21
  • 39