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

搭建8080端口Node.js服务器加载GLTF模型遇404错误求助

解决你的Node.js服务器与Three.js加载模型问题

我来帮你拆解并解决遇到的几个问题:

1. 核心问题:404错误的根源

你遇到的GET http://localhost:8080/ 404,本质是Node.js服务器读取1.html文件失败,触发了fs.readFile的错误回调。另外,即使这个问题解决了,当前服务器还会因为无法处理其他静态资源请求(比如1.js、model.gltf)导致后续模型加载失败。

修复步骤:

步骤1:确保文件路径正确

  • 确认1.html、1.js、model.gltf都放在你启动Node.js服务器的同一目录下
  • 启动服务器时,要在这些文件所在的目录运行node 你的服务端文件名.js,不要在上级目录启动

步骤2:重构服务端代码,处理不同静态资源请求

你的当前服务端代码不管请求什么路径都返回1.html,这会导致请求1.js或model.gltf时拿到的是HTML内容,进而引发错误。我们需要根据请求路径返回对应文件,并设置正确的Content-Type:

const http = require('http');
const fs = require('fs');
const path = require('path');

// 定义不同文件类型的Content-Type映射
const contentTypeMap = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.gltf': 'model/gltf+json',
  '.glb': 'model/gltf-binary',
  '.jpg': 'image/jpeg',
  '.png': 'image/png'
};

http.createServer((req, res) => {
  // 根路径默认返回1.html
  let filePath = req.url === '/' ? './1.html' : `.${req.url}`;
  const extname = path.extname(filePath);
  const contentType = contentTypeMap[extname] || 'application/octet-stream';

  fs.readFile(filePath, (error, data) => {
    if (error) {
      if (error.code === 'ENOENT') {
        // 文件不存在返回404
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.write('<h1>404 File Not Found</h1>');
      } else {
        // 服务器内部错误返回500
        res.writeHead(500);
        res.write(`Server Error: ${error.code}`);
      }
      res.end();
      return;
    }

    // 返回正确的文件内容与类型
    res.writeHead(200, { 'Content-Type': contentType });
    res.write(data);
    res.end();
  });
}).listen(8080, (error) => {
  if (error) {
    console.log(`Something went wrong: ${error}`);
  } else {
    console.log('Server is running on http://localhost:8080');
  }
});

2. HTML代码的小语法问题

你的HTML里有个未闭合的标签:<meta charset=UTF-8 应该修改为 <meta charset="UTF-8">,避免潜在的页面解析异常。

另外,你同时引入了模块脚本(Three.js相关)和非模块脚本1.js,如果1.js里使用了Three.js的API,会因为模块作用域问题导致THREE未定义。建议把1.js也改为模块脚本:

<script type="module" src="1.js"></script>

3. 关于SourceMap警告

那两个chrome-extension相关的警告是Chrome浏览器扩展的问题,和你的代码完全无关,你可以直接忽略,不会影响页面功能。如果看着不舒服,可以尝试禁用相关扩展,或者在Chrome DevTools设置里关闭「Enable JavaScript source maps」选项。


内容的提问来源于stack exchange,提问作者prinzu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:52:37