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?

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 Commented Feb 19, 2017 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? Commented May 27, 2020 at 22:32

2 Answers 2

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

3 Comments

@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.
Yes, javascript object should be passed to JSON.stringify(), see also stackoverflow.com/questions/40939857/fetch-with-readablestream
0

You can pass as below

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.