Maikon Weber Carvalho
Maikon Weber Carvalho

Reputation: 45

Sending object with params in the get method

I have this get method that receives this filter parameter, which is an object with from and I want to pass them as parameters inside the url

export async function queryEventTimelineFilteredAPI(filter) {
  
  console.log('componentManager', filter)

  
  const response = await fetch('/api/v1/data/queryEventTimeline', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  })
  return await response.json();
}

Upvotes: 0

Views: 4261

Answers (2)

Eric
Eric

Reputation: 321

Check out this jQuery function: https://api.jquery.com/jQuery.param/

Upvotes: 0

Barmar
Barmar

Reputation: 780655

Use JSON.stringify() to convert it to JSON, encodeURIComponent() to add proper % encoding of special characters, and then concatenate it to the URL.

There's no need for the Content-type header, since GET requests have no content.

export async function queryEventTimelineFilteredAPI(filter) {
  
  console.log('componentManager', filter)

  const response = await fetch('/api/v1/data/queryEventTimeline?filter=' +  encodeURIComponent(JSON.stringify(filter)), {
    method: 'GET',
  })
  return await response.json();
}

Note that URL length is generally pretty limited, so the JSON filter should not be large. It would be better to send it as POST data.

Upvotes: 3

Related Questions