make a http request with url parameters in javascript

To make an HTTP request with URL parameters in JavaScript, you can use the fetch API or the XMLHttpRequest (XHR) API. Here's an example using fetch:

index.tsx
const url = "https://example.com/api/data";
const params = {param1: "value1", param2: "value2"};

// convert params object to URL query string
const queryString = Object.keys(params)
  .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]))
  .join("&");

fetch(url + "?" + queryString)
  .then(response => {
    if (!response.ok) {
      throw new Error("HTTP error " + response.status);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));
525 chars
18 lines

In this example, url is the base URL, and params is an object containing the key-value pairs for the URL parameters. The Object.keys, encodeURIComponent, and join functions are used to convert the params object to a URL query string, which is then appended to the base URL in the fetch call.

The response is checked for errors using the response.ok property, and if the response is successful, the JSON data is logged to the console. Any errors are caught and logged to the console as well.

Note that this example assumes that the API returns JSON data, so we're using the response.json() method to parse the response. If the API returns a different data format, you'll need to use a different method to parse the response.

gistlibby LogSnag