Home > other >  Why 'blocked by CORS policy' in React, but not with Node?
Why 'blocked by CORS policy' in React, but not with Node?

Time:02-08

Running the exact same script in React is blocked by Cors policy, but not when I run it with node.

  1. Why can it be done with node, but not with React?
  2. How can I still fetch this in a React app?
  3. 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.

  •  Tags:  
  • Related