使用nodejs和html布局一个简单的视频播放网站,但是使用localhost:端口访问html无法加载视频

js代码:

javascript 复制代码
// app.js
const express = require('express');
const path = require('path');
const app = express();

// 设置静态文件目录,这里假设你的视频文件在public/videos/目录下
app.use(express.static(path.join(__dirname, '')));


// 设置主页路由,指向一个包含HTML5 video元素的页面
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'test.html'));
});

// 启动服务器
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

html代码:

html 复制代码
<!-- public/views/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Video Player</title>
</head>
<body>
    <h1>hello</h1>
  <video width="640" height="360" controls>
    <!-- 视频路径相对于static目录 -->
    <source src="./videos/111.mp4" type="video/mp4">
  </video>

  <img src="./videos/qq1.png" alt="">

  
</body>
</html>

在vscode中直接打开test.html可以正常加载视频。但是使用node 启动js监听端口然后调用test.html就不行,不能加载html文件。

文件目录结构:

--videos

--111.mp4

---qq1.png

--test.js

--test.html

问题,发现是localhost访问时地址不对。浏览器会直接访问localhost:3001/111.mp4

所以这里需要设置路径映射

其实这段代码:

javascript 复制代码
app.use(express.static(path.join(__dirname, '')));

就是用来设置路径映射的,只是最开始没有设置正确。

这里将代码改为:

javascript 复制代码
app.use(express.static(path.join(__dirname, 'videos')));

将路径映射到videos文件夹,然后就可以读取到videos文件夹下的文件。

修改后代码:

js:

javascript 复制代码
// app.js
const express = require('express');
const path = require('path');
const app = express();

// 设置静态文件目录,这里假设你的视频文件在public/videos/目录下
app.use(express.static(path.join(__dirname, 'videos')));


// 设置主页路由,指向一个包含HTML5 video元素的页面
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'test.html'));
});

// 启动服务器
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

html:

html 复制代码
<!-- public/views/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Video Player</title>
</head>
<body>
    <h1>hello</h1>
  <video width="640" height="360" controls>
    <!-- 视频路径相对于static目录 -->
    <source src="111.mp4" type="video/mp4">
  </video>

  <img src="./qq1.png" alt="">

  
</body>
</html>
相关推荐
一水鉴天21 分钟前
统一对象拓扑(UOT)设计全链定稿:从三件事分离到三继承 之1 20261010(豆包“查看聊天内容”继续)
前端·css
栖凤32 分钟前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python
粥里有勺糖32 分钟前
视野修炼第136期 | 前端小恐龙"Deno"被收购
前端·github·ai编程
修炼的dance37 分钟前
页面塞了13.88 MB字体,导出的PDF只有71 KB
前端
qq_3691736338 分钟前
如何将 AI 生成的 HTML 网页发布成在线链接?不用自己搭建服务器
前端·人工智能·html·效率工具·html 发布
风花一世月1 小时前
⚡ 我把一座含氢能源园区搬进了浏览器(五类能流实时算守恒,在线直接玩)
前端·人工智能
羲云1 小时前
Claude 越界事件之后:Agent 权限设计为什么不能只靠提示词
前端
行者全栈架构师1 小时前
【鸿蒙心迹】鸿蒙网络请求架构实战——@ohos.net.http 到 Axios 封装、拦截器与统一错误处理(HarmonyOS 7.x)
前端·算法·架构
全栈Agent 小李1 小时前
【无标题】
前端·后端·agent·ai编程·全栈·cursor·mcp
羲云1 小时前
别让 AI 凭记忆做调研:给 WorkBuddy 接上可核验的实时搜索
前端