1

I have a simple Python code to scrape a web page and it works:

from urllib.request import urlopen

url = "http://www.stackoverflow.com"
html = urlopen(url)
print(html.read())

I want a JavaScript equivalent, and I tried below:

var url = "http://www.stackoverflow.com";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
var response = xhr.responseText;

But it was blocked by CORS policy. Why Python works and JavaScript fails? Thanks.

H42
  • 725
  • 2
  • 9
  • 28
  • Does this answer your question? [Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does?](https://stackoverflow.com/questions/20035101/why-doesn-t-postman-get-a-no-access-control-allow-origin-header-is-present-on) – CherryDT Aug 04 '20 at 21:38
  • 1
    It's not JavaScript on its own that fails, it's JavaScript _in the browser inside another website_ that fails. Try node.js and it'll work. – CherryDT Aug 04 '20 at 21:39

1 Answers1

1

Python is not running on browser which implement CORS security, meaning it will not be blocked by the browser as... there is none. I invite you to take a look to MDN CORS over here : https://developer.mozilla.org/en/docs/Web/HTTP/CORS