req.query 似乎在不更改代码的情况下返回不同的值。我怎样才能让它稳定?

问题描述 投票:0回答:1

所以我尝试使用nodejs、express、ejs 和一个名为 ytdl-core 的 API 制作一个 Youtube 视频下载器。我遇到的问题是 有时 req.query 偶尔会返回 undefined 并且会产生此错误

C:\Users\mattm\Desktop\YoutubeVIdeoDownloader pp.js:17 const videoid = req.query.url.split("v=")[1]; ^ 类型错误:无法读取未定义的属性(读取“split”)

但是当它工作时,req.query 返回一个带有“url”键和输入 url 值的对象 { url: 'https://www.youtube.com/watch?v=EuJc-M35-r0' }

其他时候 req.query 返回一个带有 'link' 键和 url 值的对象

我不确定为什么会发生这种情况。我是编码新手,所以可能是我不理解逻辑。如有任何帮助,我们将不胜感激!

const express = require("express");

const ytdl = require("ytdl-core");
const app = express()
app.set("view engine", "ejs");

app.use(express.static("./public", { root: __dirname }));

// home page
app.get("/", (req, res) => {
  res.render("index");
});

//download page
app.get("/download", async (req, res) => {
  console.log(req.query);
  const videoid = req.query.url.split("v=")[1];
  const info = await ytdl.getInfo(req.query.url);
  console.log(info.formats[1]);

  return res.render("download", {
    url: "https://www.youtube.com/embed/" + videoid,
    info: info.formats.sort((a, b) => {
      return a.mimeType < b.mimeType;
    }),
  });
});

// 404 page
app.use((req, res) => {
  res.status(404).render("404");
});



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>YouTube Downloader</title>
  </head>
  <body>
    <h1 class="heading">My Own YouTube Downloader</h1>
    <form method="get" action="/download">
      <input type="text" class="URL-input" placeholder="Video URL" name="url" />
      <button type="submit" class="convert-button">Convert</button>
    </form>
  </body>
</html>

我知道它不是随机的,但似乎重置服务器有时似乎可以解决问题。我尝试使用主体解析器而不是查询,但没有成功。

node.js youtube ejs
1个回答
0
投票

有多种方法可以处理您的给定问题,但这是我对此问题的解决方案。

当 req.query() 为空时,它返回 undefined,并且 split() 方法在未定义的值上运行。因此,首先,我们需要确保 req.query() 包含我们要运行 split() 方法的预期数据。 这样做。

app.get("/download", async (req, res) => {
  const reqQuery = req.query;
  if (req.query.url) {
    const videoid = req.query.url.split("v=")[1];
    const info = await ytdl.getInfo(req.query.url);
    console.log(info.formats[1]);

    return res.render("download", {
      url: "https://www.youtube.com/embed/" + videoid,
      info: info.formats.sort((a, b) => {
        return a.mimeType < b.mimeType;
      }),
    });
  } else {
    res.json({
      message: "Something went wrong",
      error: true
    })
  }
});

在解决方案中,我没有检查 req.query(),而是检查了实际值。

原因就在这里。当我们尝试检查 req.query() 时,即使它为空, if 块也会被执行。所以一定要检查对象的内部值。

检查对象值时我们不应该在代码中犯的错误。

/* If block will be executed */
const reqQuery = {}

if (reqQuery) {
   console.log(true)
} else {
  console.log(false)
}


/* Best way */
const reqQuery2 = { url: 'https://dummyurl.com' }

if (reqQuery2.url) {
   console.log(true)
} else {
  console.log(false)
}

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.