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

基于Node/Express/Mongoose/EJS的YouTube克隆:视频渲染至iframe报错

问题描述

我使用Node.js、Express、Mongoose和EJS开发一款类似YouTube的克隆应用时,遇到了这样的问题:通过res.render()将视频链接传递到EJS文件的iframe中后,视频无法正常加载。控制台能正常打印出视频链接,但在EJS页面里就是无法生效。相关代码如下:

后端代码(index.js)

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ejs = require('ejs');

const app = express();

app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.set('view engine', 'ejs');

mongoose.connect("mongodb://127.0.0.1:27017/VidDb");

const userSchema = new mongoose.Schema({
name:{
type:String,
required:true,
unique:true
  },
email:{
type:String,
required:true,
unique:true
  },
password:{
type:String,
required:true,
  },
image:{
type:String,
  },
},{timestamps:true});

const User = mongoose.model("User",userSchema);

const vidSchema = new mongoose.Schema({
vidName:{
type:String,
required:true,
unique:true
  },
vidThumb:{
type:String,
required:true,
unique:true
  },
vidLink:{
type:String,
required:true,
unique:true
  },
likes:{
type:Number,
default:0
  },
views:{
type:Number,
default:0
  },
});

const Vids = mongoose.model("Vid",vidSchema);

app.get("/",function(req,res){
Vids.find().then(function(vids,err){
res.render("index",{
videos:vids
      });
  });
});

app.get("/vids/:vidId",function(req,res){
const videoID = req.params.vidId;
Vids.findById(videoID).then(vid => {
res.render("vid",{
video:vid
    });
  });
});

app.listen(3000,function(){
console.log("Server Started");
});

前端代码(vid.ejs)

<%- include('partials/header'); -%>
<!-- <video
    id="my-video"
    class="video-js"
    controls
    preload="auto"
    width="640"
    height="264"
    poster="MY_VIDEO_POSTER.jpg"
    data-setup="{}"
  >
    <source src="<%= video.vidLink %>" type="video/mp4" />
    <p class="vjs-no-js">
      To view this video please enable JavaScript, and consider upgrading to a
      web browser that
      <a href="https://videojs.com/html5-video-support/" target="_blank"
        >supports HTML5 video</a
      >
    </p>
  </video> -->

<iframe width="1020" height="815" src= "<%= video.vidLink %>" ></iframe>
<script src="https://vjs.zencdn.net/8.0.4/video.min.js"></script>
<%- include('partials/footer'); -%>
解决方案

1. 修复iframe的src属性格式问题

你的vid.ejs里iframe的src属性写法有误,src= "<%= video.vidLink %>" 中等号后多余的空格会导致浏览器解析URL时包含无效字符,直接去掉空格即可:

<iframe width="1020" height="815" src="<%= video.vidLink %>"></iframe>

2. 确认视频链接的嵌入格式合法性

如果你的视频是YouTube视频,不能直接使用普通的观看链接(比如https://www.youtube.com/watch?v=xxx),必须使用专属的嵌入格式链接:https://www.youtube.com/embed/xxx。

你可以在后端查询到视频后统一转换链接格式:

app.get("/vids/:vidId",function(req,res){
  const videoID = req.params.vidId;
  Vids.findById(videoID).then(vid => {
    // 针对YouTube链接做格式转换
    if (vid.vidLink.includes('watch?v=')) {
      const targetId = vid.vidLink.split('watch?v=')[1];
      vid.vidLink = `https://www.youtube.com/embed/${targetId}`;
    }
    res.render("vid",{
      video:vid
    });
  }).catch(err => {
    console.error('查询视频失败:', err);
    res.status(500).send('服务器内部错误');
  });
});

3. 补充错误处理,排查数据传递问题

在后端查询逻辑中增加错误捕获和数据校验,确保传递给EJS的视频数据是有效的:

app.get("/vids/:vidId",function(req,res){
  const videoID = req.params.vidId;
  Vids.findById(videoID)
    .then(vid => {
      if (!vid) {
        return res.status(404).send('请求的视频不存在');
      }
      console.log('传递给EJS的视频链接:', vid.vidLink); // 再次确认链接正确性
      res.render("vid",{
        video:vid
      });
    })
    .catch(err => {
      console.error('查询视频出错:', err);
      res.status(500).send('服务器错误');
    });
});

4. 在EJS中调试链接渲染结果

可以在vid.ejs中先直接输出链接文本,确认渲染后的内容是否正确:

<p>当前视频链接:<%= video.vidLink %></p>
<iframe width="1020" height="815" src="<%= video.vidLink %>"></iframe>

打开页面查看这个p标签里的链接是否和控制台打印的一致,是否存在格式错误。

内容的提问来源于stack exchange,提问作者B V S Laxman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:33:34