Issue with Downloading YouTube Videos using ytdl-core in Node.js API from React App

464 Views Asked by At

I am currently working on a project where I need to download YouTube videos using the ytdl-core library in a Node.js API. The video download functionality is intended to be accessed from a React app through an API request. While the video gets downloaded successfully, I'm encountering an issue where the downloaded video doesn't seem to open properly.

Here's the relevant code I'm using:

Node.js API:

const express = require('express');
const cors = require('cors');
const ytdl = require('ytdl-core');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;

app.use(cors());
app.use(bodyParser.json());

app.post('/download', async (req, res) => {
  const videoURL = req.body.url;

  if (!videoURL) {
    return res.status(400).json({ error: 'Missing video URL' });
  }

  try {
    const info = await ytdl.getInfo(videoURL);
    const videoFormat = ytdl.chooseFormat(info.formats, { quality: 'highest' });

    res.header('Content-Disposition', `attachment; filename="${info.videoDetails.title}.mp4"`);
    ytdl(videoURL, { format: videoFormat }).pipe(res);
  } catch (error) {
    res.status(500).json({ error: 'An error occurred while processing the request' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

React App:

const testRequest = async () => {
    try {
      const response = await axios.post('http://localhost:3000/download', {
        url: 'https://www.youtube.com/watch?v=zBjJUV-lzHo&ab_channel=MEMESHUB'
      });

      const blob = new Blob([response.data]);
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = 'video.mp4';
      document.body.appendChild(link);
      link.click();
      
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    } catch (error) {
      console.error('Error downloading video:', error);
    }
  };

Issue that I mentioned

I've noticed that although the video is downloaded, attempting to open the downloaded video results in an issue. Could anyone help me identify what might be causing this problem? Is there something wrong with my approach or the way I'm using the ytdl-core library? Any insights or suggestions would be greatly appreciated. Thank you in advance!

0

There are 0 best solutions below