Running the exact same script in React is blocked by Cors policy, but not when I run it with node.
- Why can it be done with node, but not with React?
- How can I still fetch this in a React app?
- It's also allowed in this chrome extension, is that because the script is executed visiting youtube so that domain is youtube?
async function isThisAllowed() {
const videoURL = `https://www.youtube.com/watch?v=QnQe0xW_JY4`
const data = await axios.get(videoURL);
console.log(data);
}
CodePudding user response:
CORS is a way for websites (in this case YouTube) to prevent other domains from accessing them. Basically, in this case, scripts running on other domains will not be able to access youtube.com
.
CORS is only enforced by browsers, so it makes sense that your Node script would work as expected while your React app wouldn't.
Here's a good explanation of how CORS works.
You could fix this with a simple Node proxy:
import express from "express";
import axios from "axios";
const app = express();
app.get("/proxy", async (req, res) => {
const resp = await axios.get(req.query.url);
res.send(resp.data);
});
app.listen(process.env.PORT || 3000);
CodePudding user response:
CORS is a feature in web browsers used by websites to prevent access to external domains (e.g. youtube.com).
The Mozilla docs have a very good explanation of this.
If you wish to access data from Youtube, I would recommend creating your own API (via Node.js) which gets data from Youtube (ideally from their API instead of straight from the site - this should be easier to work with and have less issues) and caches this, and then your API serves this data to your React app.