bypass cors in client in javascript

To bypass CORS in JavaScript, you can use the fetch API or XMLHttpRequest (XHR) to make requests to a server that is in a different domain than the one serving your web page. Here's an example of how to use the fetch API to make a GET request to a remote API that does not have CORS enabled:

index.tsx
fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
151 chars
5 lines

By default, browsers will block cross-domain requests due to the security risks involved. To bypass this restriction, you can use a proxy server to make the request on your behalf, or you can add the appropriate CORS headers on the server-side response.

If you want to use XHR instead of fetch, you can do the following:

index.tsx
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data', true);
xhr.onload = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var data = JSON.parse(xhr.responseText);
    console.log(data);
  }
};
xhr.onerror = function (error) {
  console.error(error);
};
xhr.send();
313 chars
13 lines

gistlibby LogSnag