3
votes

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?

2
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
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

2 Answers

5
votes

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(...);
0
votes

You can pass as below

 fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})