<scripts> 节点 js 加载失败

Loading failed for <scripts> node js

我尝试在 Node.js 服务器(v10.15.0 + express,socket.io)客户端的 index.html 中使用我的 Room.js。 我不断收到错误。 当我通过 index.html 文件中的脚本标签加载它时,控制台给了我一个

Loading failed for "script" with .. "Room.js".
ReferenceError: Room is not defined

当我像这样在 app.js 中使用 require 时:

const roomObj = require("./client/js/Room.js");
const Room = new roomObj();

我只得到这个错误

ReferenceError: Room is not defined

Room.js

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(){}
}

index.html

<script src="./js/Room.js"></script> 
<script>
 function loadRoom(){
   let room = new Room(name, o, obs, ep);
   room.loadRoom();
 }
</script>

更新

Getting 404 Error for Room.js

当访问 localhost:2000/js/ 和以下子目录时,我得到了

Cannot GET /js/ and the same result for every other Path

解决方法:(来自回答中的评论)
将 app.js 中的第 5-7 行替换为

app.use(express.static(__dirname + "/client"));

首先,检查 Room.js 是否与 Web 服务器上的 index.html 位于同一目录中。从您的第一个错误来看,似乎找不到脚本文件。

如果不是,请将它们移动到同一目录或更正 inde.html 中的脚本标记。如果这不起作用,请参阅下面的另一种可能的解决方案。

评论后更新:

如果JS文件在./js/Room.js,你需要将HTML文件中的脚本指向它。

<script src="./js/Room.js"></script> 
<script>
 function loadRoom(){
   let room = new Room(name, o, obs, ep);
   room.loadRoom();
 }
</script>

讨论后更新:

服务器 (Express) 在根目录中加载 index.html,在 Web 服务器的子目录中加载 client

您可以删除第 5-7 行(来自您的 link)并替换它们 app.use(express.static(__dirname + "/client"));。这会将 client 加载到 Web 服务器的根目录。

请注意,您可能仍会遇到以下错误。


在浏览器中,module 未定义,因此 module.exports 会给出错误并且脚本将失败。

您应该从 Room.js 中删除第 module.exports = Room; 行,这样文件才能在浏览器中正确加载。但它不会在 Node.js 脚本中工作,因为函数 Room 不会从文件中导出。

如果您需要在 Node.js 和浏览器中使用相同的文件,我建议您使用 Gulp、Webpack、Browserify、Parcel 或其他网络应用程序捆绑器。