使用 Javascript 检查 Youtube 频道是否直播,而不使用 API

rob*_*ron 0 javascript youtube

我发现这个 Javascript 是为了检查如何查明 YouTube 频道是否上线,但我被 CORS 政策阻止了,我想知道如何修复它?谁能帮我?来源检查 Youtube 频道是否直播,无需使用 API

var channelid = "UCnB-Fhp5FQfCZNfdAvm27Qw"; // REPLACE WITH YOUR CHANNEL ID

function onlive() {
  // DO SOMETHING IF CHANNEL IS LIVE STREAMING
}

/* REST OF THE CODE */

fetch('https://www.youtube.com/channel/' + channelid).then(function (response) {
    return response.text();
}).then(function (html) {
  if (html.includes("hqdefault_live.jpg")) {
onlive();
  }
}).catch(function (err) {
    console.warn('Something went wrong', err);
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 5

不幸的是,您无法向https://www.youtube.com发出客户端请求并避免 CORS 政策,因为它是浏览器上的内置系统,用于拒绝像您这样的人的请求 =)

但。

我们可以通过代理服务器端请求并伪装成客户端来避免 CORS 策略。之后,您可以将所有逻辑移至您的服务器。

  1. index.js在本地主机上创建包含下一个内容的文件

   // Import the required http module
const http = require('http');
const https = require('https');
const url = require('url');

function youtubeRequest(channelId, headers) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'www.youtube.com',
      path: `/channel/${channelId}`,
      method: 'GET',
      headers: headers
    };

    let raw = ''

    const req = https.request(options, (res) => {
      res.on('data', (d) => {
        raw += d;
      });

      res.on('end', () => {
        resolve(raw);
      });
    });

    req.on('error', (error) => {
      console.log(error);
      reject(error);
    });


    req.end();
  });
}

// Define the request handler function
const requestHandler = async (req, res) => {
  const parsedUrl = url.parse(req.url, true);


  // Check if the request method is GET and the path is '/call'
  if (req.method === 'GET' && parsedUrl.pathname === '/isLive') {
    const channelId = parsedUrl.query.channelId;

    if (!channelId) {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      const jsonResponse = { message: 'Channel id is invalid' };
      res.end(JSON.stringify(jsonResponse));

      return;
    }

    try {
      const HTML = await youtubeRequest(channelId, {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language": "en,ru-RU;q=0.9,ru;q=0.8,en-US;q=0.7",
        "cache-control": "max-age=0",
      });

      let isLive = false;

      if (HTML.includes("hqdefault_live.jpg")) {
        isLive = true;
      }

      res.writeHead(200, {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
        'Content-Type': 'application/json'
      });

      // Send a JSON response
      const jsonResponse = {
        isLive,
        message: isLive ? 'Your channel is live' : 'Your channel disabled'
      };
      res.end(JSON.stringify(jsonResponse));
    } catch (e) {
      console.log(e);
      res.writeHead(500, { 'Content-Type': 'application/json' });

      // Send a JSON response
      const jsonResponse = { message: 'Something went wrong, check your server logs' };
      res.end(JSON.stringify(jsonResponse));
    }
  } else {
    // Send a 404 response for other routes
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not found');
  }
};

// Create the server with the request handler
const server = http.createServer(requestHandler);

// Start the server listening on a specified port
const port = 3000;
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Run Code Online (Sandbox Code Playgroud)

  1. 使用 bash 命令启动它node index.js。如果你还没有安装NodeJs,你可以通过官方网页安装。

之后,您的服务器应该运行在http://localhost:3000

  1. 现在,您可以向客户提出请求http://localhost:3000/isLive?channelId=UCnB-Fhp5FQfCZNfdAvm27Qw

因此,使用下面的客户端 JavaScript 来调用您的 Web 服务器

<script>
  var channelid = "UCnB-Fhp5FQfCZNfdAvm27Qw"; // REPLACE WITH YOUR CHANNEL ID
  fetch('http://localhost:3000/isLive?channelId=' + channelid).then(function (response) {
    return response.text();
  }).then(function (response) {
    console.log(response);
  }).catch(function (err) {
    console.warn('Something went wrong', err);
  });
</script>
Run Code Online (Sandbox Code Playgroud)

现在,在浏览器控制台中,您可以看到结果 页面截图