make a http request with a custom header in javascript

Here's an example of making an HTTP request with a custom header using the fetch API in JavaScript:

index.tsx
fetch('https://example.com/api/data', {
  headers: {
    'Custom-Header': 'custom-value'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
209 chars
9 lines

In this example, we are making a GET request to https://example.com/api/data with a custom header named Custom-Header and a value of custom-value. Once the response is received, we are parsing its JSON representation and logging it to the browser console. If there's an error fetching the data, we log the error to the console as well.

You can also use the XMLHttpRequest (XHR) object to make HTTP requests with custom headers. Here's how:

index.tsx
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.setRequestHeader('Custom-Header', 'custom-value');
xhr.onload = function() {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Request failed. Returned status of ' + xhr.status);
  }
};
xhr.send();
363 chars
13 lines

In this example, we are creating a new XHR object, opening a GET request to https://example.com/api/data, setting a custom header using the setRequestHeader method, defining a callback function to handle the response, sending the request using the send method, and parsing the JSON representation of the response data. If the request fails, we log an error message to the console.

gistlibby LogSnag