'CORS error on using XMLHttpRequest() but allowing fetchAPI call?
i am trying to parse a webpage, on using fetch getting response from server but when i use XMLHTTPrequset it is being blocked with cors ploicy
1. Call using fetch ---> code below --> getting proper response .
const getData = async () => {
const l = [];
const res = await fetch("https://time.com/");
const data = await res.text();
const dom = new jsdom.JSDOM(data);
const t = dom.window.document.querySelectorAll("div.latest-stories>ul>li");
t.forEach((e) =>
l.push({
title: e.childNodes[1].children[0].innerHTML,
link: `https://time.com/${e.childNodes[1].href}`,
})
);
return l;
};
getData().then((e) => console.log(e));
2. failing using xmlhttprequest --> code below
Request failed as blocked by cors (no access-control-allow-origin present in server response)
qusetion is how fetch makes it possible and to do so from browser what should be done ????
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log(this.responseText);
};
xhr.open("GET", "https://time.com/", true);
xhr.send();
</script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
