You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React应用中使用Node.js模块ytdl-core实现YouTube视频下载

在React应用中使用ytdl-core实现YouTube视频下载

首先要明确:ytdl-core是Node.js专属模块,无法直接在浏览器端的React代码中使用——它依赖Node.js的文件系统、HTTP模块等浏览器不具备的API,同时YouTube接口存在CORS限制,前端直接调用会触发跨域错误。正确的实现方式是搭建一个Node.js后端服务,通过接口处理下载逻辑,前端仅负责传递视频URL并触发下载流程。

步骤1:搭建Node.js后端服务

  1. 新建后端项目目录并初始化npm:
mkdir ytdl-backend && cd ytdl-backend
npm init -y
  1. 安装所需依赖:
npm install express ytdl-core cors
  1. 创建server.js文件,编写下载接口:
const express = require('express');
const ytdl = require('ytdl-core');
const cors = require('cors');
const app = express();

// 处理跨域请求
app.use(cors());
app.use(express.json());

// 视频下载接口
app.get('/download', async (req, res) => {
  try {
    const videoUrl = req.query.url;
    // 校验URL有效性
    if (!ytdl.validateURL(videoUrl)) {
      return res.status(400).send('无效的YouTube视频链接');
    }

    // 获取视频信息,设置下载文件名
    const videoInfo = await ytdl.getInfo(videoUrl);
    const safeTitle = videoInfo.videoDetails.title.replace(/[^\w\s]/gi, '');
    res.header('Content-Disposition', `attachment; filename="${safeTitle}.mp4"`);
    
    // 流式传输视频到前端
    ytdl(videoUrl, { quality: 'highest' }).pipe(res);
  } catch (err) {
    res.status(500).send('下载失败:' + err.message);
  }
});

// 启动服务
const PORT = 3001;
app.listen(PORT, () => {
  console.log(`后端服务运行在 http://localhost:${PORT}`);
});
  1. 启动后端服务:
node server.js

步骤2:修改React前端代码

更新你的Input组件,让下载函数向后端接口发送请求,触发浏览器下载:

import React, { useState } from 'react'

function Input() {
  const [url, setUrl] = useState("");
  const [errorMsg, setErrorMsg] = useState("");

  const downloadVideo = () => {
    if (!url.trim()) {
      setErrorMsg('请输入YouTube视频链接');
      return;
    }

    try {
      // 构造后端请求地址,打开新标签触发下载
      const downloadLink = `http://localhost:3001/download?url=${encodeURIComponent(url)}`;
      window.open(downloadLink, '_blank');
      setErrorMsg("");
    } catch (err) {
      setErrorMsg('请求失败:' + err.message);
    }
  }

  return (
    <div className="p-4">
      <h1 className="text-3xl font-bold mb-4">Youtube Video Downloader</h1>
      {errorMsg && <p className="text-red-500 mb-4">{errorMsg}</p>}
      <input
        type="text"
        onChange={(e) => setUrl(e.target.value)}
        className="border border-gray-300 rounded px-3 py-2 w-full mb-4"
        placeholder="Enter video URL"
        value={url}
      />
      <button
        onClick={downloadVideo}
        className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
      >
        Download
      </button>
    </div>
  )
}

export default Input

关键注意事项

  • 跨域处理:后端通过cors中间件解决跨域问题,确保前端能正常请求接口。
  • 视频质量配置:代码中使用quality: 'highest'获取最高质量视频,你可根据需求调整参数,比如指定分辨率、音频格式等。
  • 依赖更新:YouTube接口会频繁变动,需定期更新ytdl-core到最新版本,避免解析失败。
  • 合规性提醒:未经授权下载YouTube视频可能违反其服务条款,使用前请确认行为合规。

内容的提问来源于stack exchange,提问作者Kevin Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:36:18