问题
THE PROBLEM IS ABOUT YOUTUBE NOT MEDIUM
According to How to use Cors anywhere to reverse proxy and add CORS headers you just need to append url. It works for medium url but not for youtube url (I tried in Chrome dev tools)
getTitle = (url) => {
return fetch(`https://cors-anywhere.herokuapp.com/${url}`,
{method: 'GET',
header:('Access-Control-Allow-Headers: *, X-Requested-With, Content-Type, Accept'),
mode: 'cors'}
)
.then((response) => response.text())
.then((html) => {
const doc = new DOMParser().parseFromString(html, "text/html");
const title = doc.querySelectorAll('title')[0];
return title.innerText;
});
};
var urls = [
'https://medium.com/@unakravets/the-sad-state-of-entitled-web-developers-e4f314764dd',
'https://www.youtube.com/watch?v=AGFbS_jdSl0&origin=https://youtube.com',
]
// This one keeps the order the same as the URL list.
Promise.all(
urls.map((url) => getTitle(url))
).then((titles) => {
console.log(titles);
});
error message:
Access to fetch at 'https://www.youtube.com/watch?v=AGFbS_jdSl0' (redirected from 'https://cors-anywhere.herokuapp.com/https://www.youtube.com/watch?v=AGFbS_jdSl0') from origin 'https://www.youtube.com' 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.
I tried to change mode to no-cors as recommanded in error message, but it's even worse
VM69:11 Uncaught (in promise) TypeError: Cannot read property 'innerText' of undefined
来源:https://stackoverflow.com/questions/62006628/why-cors-anywhere-herokuapp-com-doesnt-work-with-youtube