make a http request with url parameters in typescript

To make an HTTP request with URL parameters in TypeScript, you can use a third-party library like Axios or use the built-in Fetch API.

Here is an example using Axios to make a GET request with URL parameters:

index.ts
import axios, { AxiosResponse } from 'axios';

const apiUrl = 'https://example.com/api';
const params = {
  id: 123,
  name: 'John Doe'
};

axios.get(apiUrl, { params })
  .then((response: AxiosResponse) => {
    console.log(response.data);
  })
  .catch((error: any) => {
    console.error(error);
  });
305 chars
16 lines

In this example, we are importing Axios and the AxiosResponse interface from the axios package. We declare the API endpoint URL and the parameters object. Then we call the get method on the axios object with the API URL and the params object as the second argument. The get method returns a promise that resolves with the response data.

If you prefer to use the Fetch API, here is an example:

index.ts
const apiUrl = 'https://example.com/api';
const params = {
  id: 123,
  name: 'John Doe'
};

const queryParams = new URLSearchParams(params).toString();

fetch(`${apiUrl}?${queryParams}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
301 chars
13 lines

In this example, we declare the API endpoint URL and the parameters object. We convert the parameters object into a string using the URLSearchParams constructor and the toString method. Then, we call the fetch method with the endpoint URL and the parameters string as a query string. The fetch method returns a promise that resolves with the response data. We then use the json method to parse the response data into a JSON object.

gistlibby LogSnag