本地测试TensorFlow.js的COCO-SSD模型:Web服务器托管文件指什么?
为什么
file://协议不行? 直接双击用file://协议打开HTML文件时,浏览器出于安全限制,会阻止跨域资源请求——TensorFlow.js加载COCO-SSD模型时需要读取模型权重文件,这种操作在file://协议下会被浏览器拦截,导致模型加载失败,自然没法正常检测。
用Node.js搭建本地Web服务器的几种方法
因为你熟悉Node.js,给你三个简单可行的方案:
1. 用Node.js内置http模块(无需额外安装包)
在项目根目录新建server.js文件,写入以下代码:
const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { let filePath = '.' + req.url; if (filePath === './') { filePath = './index.html'; // 默认加载主页文件 } const extname = path.extname(filePath); let contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpeg'; break; } fs.readFile(filePath, (error, content) => { if (error) { if(error.code === 'ENOENT'){ res.writeHead(404); res.end('File not found'); } else { res.writeHead(500); res.end('Server Error: ' + error.code); } } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); }); const PORT = 8080; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
终端运行命令启动服务器:
node server.js
最后打开浏览器访问http://localhost:8080即可加载项目。
2. 用http-server包(快捷省心)
这是专门用来快速搭建静态文件服务器的工具,步骤如下:
- 全局安装工具(仅需一次):
npm install -g http-server
- 进入项目根目录,运行启动命令:
http-server
终端会输出服务器地址(比如http://localhost:8080),直接访问该地址即可。
3. 用Express框架(适配已有Express项目)
如果平时常用Express,可按以下步骤操作:
- 初始化项目(未初始化时执行):
npm init -y
- 安装Express依赖:
npm install express
- 新建
server.js文件:
const express = require('express'); const app = express(); const path = require('path'); // 托管当前目录下的所有静态文件 app.use(express.static(__dirname)); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
- 启动服务器:
node server.js
访问http://localhost:3000即可加载项目。
后续操作
把你的HTML、JS文件,以及本地存放的COCO-SSD模型文件(如果有的话)都放在服务器托管的目录下,然后用浏览器访问对应的HTTP地址,就能正常加载模型并完成目标检测了。
内容的提问来源于stack exchange,提问作者Rhodey
相关产品推荐
相关产品推荐

