how to send complex object in get request in typescript

To send a complex object in a GET request in TypeScript, you generally have two options:

  1. Query Parameters: You can serialize the complex object and send it as query parameters.
  2. Path Parameters: You can serialize the complex object and send it as part of the endpoint URL.

Here's an example of how you can achieve this using query parameters:

index.ts
const complexObject = {
  key1: 'value1',
  key2: 'value2'
};

const queryString = new URLSearchParams(complexObject).toString();
const url = `https://your-api-endpoint.com/data?${queryString}`;

fetch(url, {
  method: 'GET'
})
  .then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
453 chars
20 lines

In this example, complexObject is serialized into query parameters using URLSearchParams and then appended to the endpoint URL. Finally, a GET request is made to the API.

Remember that sending complex objects in a GET request is less common due to limitations like URL length restrictions. It's usually more appropriate to send complex objects in the request body of a POST request for better readability and security.

related categories

gistlibby LogSnag