0

I would like to make a simple http request in javascript with fetch(), eg.:

async function fetchData() {
  const res = await fetch("https://www.google.com");
  console.log(res);
}

fetchData();

but this fails with:

Access to fetch at 'https://www.google.com/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

There are lots of posts about this in internet and the most popular solutions revolve around setting up additional headers, I tried this as well, but it did not help:

const res = await fetch("https://www.google.com", {
    headers: {
      mode: "cors",
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*",
    },
  });
}
// ...

This perfectly works with curl: curl "https://www.google.com".

Any ideas?

VCODE
  • 535
  • 5
  • 19
  • What is the overarching problem that you are trying to solve with this code? – Yogi Nov 26 '22 at 21:21
  • I would like to make an http request to a webpage and extract a subset of content from the html body. – VCODE Nov 26 '22 at 21:23
  • So, it's a request to an `.html` page, not some protected API, so I am wondering why wouldn't it work?.. I should mention also that I have zero experience in web development, so maybe this is basic stuff. Is there a way to achieve what I want, i.e: download the content of a `.html` page? – VCODE Nov 26 '22 at 21:28
  • You can fetch data from an API because that's what it is design to do, but html is blocked except under a narrow set of conditions. As an alternative, you might look at building a [browser extension](https://chrome.google.com/webstore/detail/instant-data-scraper/ofaokhiedipichpaobibbnahnkdoiiah?hl=en) as those aren't limited by CORS. And extensions aren't difficult to [create](https://developer.chrome.com/docs/extensions/mv3/getstarted/). – Yogi Nov 26 '22 at 23:11
  • Yes CORS can be enabled using Headers, but they must be set by the server not the client. – Evert Nov 27 '22 at 02:26

0 Answers0