我正在尝试在前端使用 ytdl-core 和 ReactJS 来获取 YouTube 视频的直接链接,然后使用它们从中获取音频和视频,我还想将音频放在标签上。但问题是我运行时遇到错误:
useEffect(() => {
(async () => {
const stream = ytdl(LINK, {
filter: "audioonly",
format: "webm",
}).on("error", (error) => console.log(error));
})();
});
我得到的错误是:“
Access to fetch at 'https://www.youtube.com/watch?v=blablablabl' from origin 'http://localhost:3000' 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.
”
我真的很感激有关此事的一些帮助
我尝试使用 corsAnywhere,但从 ytdl-core 收到一条错误消息,提示“不是 YouTube 域”。 这就是我尝试实现它的方式:
useEffect(() => {
(async () => {
const stream = ytdl(`https://cors-anywhere.herokuapp.com/${LINK}`, {
filter: "audioonly",
format: "webm",
}).on("error", (error) => console.log(error));
})();
});
确保您在节点中安装了cors。尝试使用此代码。
import cors from "cors";
const corsOptions = {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
app.use(cors(corsOptions));