2

I'm trying to fetch data from a different origin to another server using Fetch API and I precise is from http to https

I can read the data from my browser but I don't know how to fetch them.

I already tried to set Access-Control-Allow-Origin to * but I still get this message :

console

I'm a little bit lost right know, Thank you for your support.

const myHeaders = new Headers({
  "Access-Control-Allow-Origin": "*",
  "Content-Type": "application/json"
});

const fetchConfig = {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "no-cache"
};

function fetchData(url) {

  fetch(url, fetchConfig)
    .then(response => {
      return response.json();
    })
    .then(data => {
      console.log(data);
    })
    .catch(error => console.error(error));

}

fetchData("https://api.example.com/");
Olivier.C
  • 171
  • 2
  • 11

2 Answers2

3

The Access-Control-Allow-Origin header needs to be set by the server you are retrieving the data from, in response to your request.

Chris Wheeler
  • 1,623
  • 1
  • 11
  • 18
1

CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The URL to the proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example, to avoid a direct visit from the browser.

You can simply add https://cors-anywhere.herokuapp.com/ at the beginning of your url. Like this https://cors-anywhere.herokuapp.com/http://example.com/api/....

Check this link for more details: https://www.npmjs.com/package/cors-anywhere