1

I wanted to know how I can use the fetch() function in javascript to return the source of a page from a different origin. I already know that if you want to get the HTML source you do something like this:

const getData = async () => {
  const res = await fetch('http://example.com')
  const data = await res.text()
  console.log(data)
}

When I tried using the above function, I got a cors error. I then tried adding, {mode: 'no-cors'} to the options but, that didn't return any response. I have done some research and found nothing useful. Is it possible to get the source of a website from a cross-origin request? Thanks.

Moataz
  • 175
  • 7
  • If the source is "SOP protected" you can't. Use your server as a proxy to get the markup of a third-party page. – Teemu Dec 20 '22 at 11:41
  • `no-cors` is how you tell `fetch` you don't intend to access the response. You **can't** use browser-hosted JavaScript to bypass the Same Origin Protocol. If you could, the SOP would be pointless. I suggest reading up on the [SOP](https://en.wikipedia.org/wiki/Same-origin_policy). (The server of the page you're trying to read could relax the SOP rules via [CORS](https://fetch.spec.whatwg.org/#http-cors-protocol), but if they don't, they don't.) – T.J. Crowder Dec 20 '22 at 11:49

0 Answers0