Employ the fetch method to perform a get request along with a data object

In my current project, I am utilizing the Fetch API and I am looking to streamline the process by creating a function that can handle various parameters like method, url, and data in order to create the appropriate request for both GET and POST methods.

I am curious if it is feasible to use Fetch to send a data object where for a GET request, the data is converted into a string of parameters within the URL, and for a POST request, the data object is sent in the body of the request?

An example scenario would be:

fetch ('/test', {
        method: 'GET',
        data: {
           test: 'test'
        }
});

This question arose from observing similar behavior in jQuery ajax requests:

$.ajax({
   url: '/test',
   method: 'GET',
   data: {
      test: 'test'
   }
});

Which would result in the following request:

'/test/?test=test'

Answer №1

In the scenario where I include the data object in the fetch constructor for a GET request, will it send the request as shown in my example '/test/?test=test'?

If you need to incorporate a query string into a fetch request:

Referencing the SPEC

var url = new URL("https://a.com/method"),
params = {a:1, b:2}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url)

this action will generate a request :

https://i.sstatic.net/IBADk.jpg

Answer №2

To achieve the desired outcome, you have two options available:

var url = new URL("/test/")
Object.keys({test: 'test', a: 1}).forEach(key => url.searchParams.append(key, params[key]))
fetch(url);

Alternatively, if wider browser support is required, you can manually parse the string like this:

var params = {test: 'test', a: 1},
    qs = Object.keys(params).reduce(function(_qs, k, i){ return _qs + '&' + k + '=' + params[k]; }, '').substring(1);

console.log(qs)

Answer №3

Learn how to create queries with or without utilizing URLSearchParams.

If you're working with typescript, the code snippets are in typescript. If not, simply remove types as it will still function correctly.

Straightforward Approach (Using URLSearchParams)

/**
 * Generates query from provided object
 * - Does not handle deep nesting
 * - Does not eliminate empty fields
 * @returns `state1=6&state2=horse` without `?`
 */
function createQuery(queryObject?: Record<string | number, unknown> | null): string {
  if (queryObject == null) return ""
  const searchParams = new URLSearchParams(queryObject as Record<string, string>)
  return searchParams.toString()
}

Problem Solving Approach (Using URLSearchParams)

/**
 * Generates query from provided object
 * - Does not handle deep nesting
 * - Eliminates empty fields
 * @returns `state1=6&state2=horse` without `?`
 */
function createQuery(queryObject?: Record<string | number, unknown> | null): string {
  if (queryObject == null || !Object.keys(queryObject).length) return ""
  for (const key in queryObject) {
    if (Object.prototype.hasOwnProperty.call(queryObject, key)) {
      const value = queryObject[key]
      if (value == null) delete queryObject[key]
    }
  }
  const searchParams = new URLSearchParams(queryObject as Record<string, string>)
  return searchParams.toString()
}

Alternative to URLSearchParams

/**
 * Generates query from provided object
 * - Supports prefixes
 * - Supports deep nesting
 * - Eliminates empty fields
 * @returns `state1=6&state2=horse` without `?`
 */
function createQuery(queryObject?: Record<string | number, unknown> | null, keyPrefix?: string): string {
  if (queryObject == null || !Object.keys(queryObject).length) return ""
  keyPrefix = keyPrefix ? (keyPrefix + "_") : ""

  const queryKeys = Object.keys(queryObject)
  const queryArray = queryKeys.map(key => {
    const value = queryObject[key]
    // additional logic for nested objects can be added here
    return keyPrefix + encodeURIComponent(key) + "=" + encodeURIComponent(String(value))
  })

  return queryArray.filter(Boolean).join("&")
}

Helper Function: isDictionary

The isDictionary helper function referenced above can be found here

How to Use

Add a ? at the start of your endpoint followed by createQuery

fetch("/test?" + createQuery({ foo: 12, bar: "@user->here", object: { test: "test", bird: { super: { ultra: { mega: { deep: "human" }, shop: 7 } }, multiple: [1, 2, 3] } } }))
Output
foo=12&bar=%40user-%3Ehere&object_test=test&object_bird_super_ultra_mega_deep=human&object_bird_super_ultra_shop=7&object_bird_multiple=1%2C2%2C3

or

foo: 12
bar: @user->here
object_test: test
object_bird_super_ultra_mega_deep: human
object_bird_super_ultra_shop: 7
object_bird_multiple: 1,2,3

https://i.sstatic.net/p3AKe.png

In Conclusion

Choose from various code snippets based on your specific requirements and objectives.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...

Initial function call to modify the state does not result in any field updates

As I delve into integrating GraphQL with a React web application for testing and educational purposes, I am humbly admitting to being a newbie in this domain. To provide a brief overview, I am working on a book library application, where we have a compila ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...

How to retrieve a specific value using jQuery based on the name attribute

I'm having an issue retrieving the selected value from the menu and assigning it to the `country` variable. Whenever I try, I keep encountering the error: No parameterless constructor defined. The `UpdateClient` function is triggered by clicking on t ...

Creating a hover effect for a specific card while maintaining the rest of the cards unaffected

When hovering over a card, all icons are displayed instead of just the icons for that specific card. I want to show only the icons for the card being hovered on (example output: image). The cards are generated automatically using v-for and fetching data fr ...

The error message keeps appearing consistently. What is the best way to manage this error?

Even after entering the data in this field, it was supposed to disappear. However, that didn't happen as expected. <md-input-container class="md-block" flex-gt-sm> <label>Budget</label> <input name="budget" ng-model="newTri ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Dynamic updating of Laravel models

I am facing an issue with my website where a series of posts are displayed upon loading, sent to the page using a controller in the following return statement: return View::make('stream')->with($this->postStream()); The postStream functio ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Encountering a 400 error while using Stripe CLI to listen for webhooks on localhost

Good day everyone! I've been encountering a 400 error when trying to listen to stripewebhooks. The command I'm using is: stripe listen --forward-to localhost:3000/stripe/webhooks After a successful payment: 2024-02-11 19:03:48 --> charge.suc ...

Tips for transferring binary information from a Node.js socket.io (v2.0.x) server to a client in a web browser

When using Engine.io's send function to send binary data, it appears as binary in DevTools. However, Socket.io handles this data as JSON and sends it as text. Is there a way to access the Engine.io send function through a Socket.io instance? Perhaps ...

Tips on storing a blob (AJAX response) in a JSON file on your server, not on the user's computer

After researching extensively on creating a URL from or downloading a blob in a computer, I require a unique solution: (1) Save a blob in own server into a JSON file, (2) Optimize the way to update a database using the data stored in the JSON. My attemp ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

Obtaining the image with PHP

As a newcomer to PHP and Ajax queries, I am trying to utilize the croppie.js plugin to upload a profile image. However, when I upload the image, it is saved as 1580192100.png. The problem arises when attempting to later retrieve the image based on the user ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

How to implement pagination with subdocuments in Node.js using Mongoose

My attempt to paginate a subcomment named "Items" within a collection using mongoose-paginate-v2 has not been successful. Below is my model: const mongoosePaginate = require('mongoose-paginate-v2'); const PettyCashItemsSchema = ...

Discovering techniques to minimize the need for prop drilling in ReactJS component trees

As I was reading through the ReactJS documentation, I stumbled upon the section about Contexts where I found the following information: The page mentioned that if you only need to avoid passing certain props through multiple levels, using component compo ...

The onUpdate function does not seem to be functioning as expected in the react-custom-scrollbars

In my React.js application, I am utilizing the "react-custom-scrollbars" component. My goal is to invoke a method each time a user scrolls. To achieve this, I have attempted using the onUpdate method. <div className="thumbs-panel"> <Scrollbar ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...