【发布时间】:2019-07-13 05:05:10
【问题描述】:
我尝试在我的 Node.js 服务器(v10.15.0 + express,socket.io)客户端的 index.html 中使用我的 Room.js。 我不断收到错误。 当我通过 index.html 文件中的脚本标签加载它时,控制台给了我一个
使用 ..“Room.js”加载“脚本”失败。
ReferenceError: 房间未定义
当我像这样在 app.js 中使用 require 时:
const roomObj = require("./client/js/Room.js");
const Room = new roomObj();
我只得到这个错误
ReferenceError:房间未定义
module.exports = Room;
function Room(name, o, obs, ep){
this.name = name;
this.o = o;
this.obs = obs;
this.getSth = function(ep){}
this.loadRoom = function(){}
}
<script src="./js/Room.js"></script>
<script>
function loadRoom(){
let room = new Room(name, o, obs, ep);
room.loadRoom();
}
</script>
更新
Room.js 出现 404 错误
当访问 localhost:2000/js/ 和以下子目录时,我得到了
无法获取 /js/ 并且所有其他路径的结果都相同
解决方案:(来自评论中的回答)
将 app.js 中的第 5-7 行替换为
app.use(express.static(__dirname + "/client"));
【问题讨论】:
-
查看您的网络检查器,看看您是否没有收到 404 错误。
-
Room.js是否与 Web 服务器上的index.html位于同一目录中?你使用 Webpack 还是其他构建工具? -
另外,您使用哪种浏览器?如果我尝试重现您的问题,我会收到
'module' is not defined错误。 -
@Imarqs 是的,我收到 404 错误
-
@Filip 我使用的是 firefox 65.0.1x64,路径是 ./index.html 和 ./js/Room.js
标签: javascript node.js loading