NodeJS+MongoDB开发MMORPG遇document未定义错误求助
Hey there! Let's break down why you're hitting this ReferenceError: document is not defined error when starting your server—it's a super common gotcha when mixing client-side and server-side code in Node.js projects.
What's Causing the Error?
The document object is a browser-only DOM API—it doesn't exist in the Node.js server environment. From your app.js snippet, I see you're using require('./client/inventory') to load the inventory.js file directly into your Node.js server process. If your refreshRender() function in inventory.js uses document (like updating on-screen inventory UI elements), the server will throw this error the second it tries to execute that code.
On top of that, if your entity.js (a server-side module, I assume) is calling refreshRender(), that's another red flag—server-side code should never try to manipulate browser DOM elements directly.
Step-by-Step Fixes
Separate Client and Server Code
First, remove the client-side inventory.js from your server's require chain. In app.js, delete this line:// 删掉这行——不要在服务器端加载客户端专属代码 // require('./client/inventory');Instead, load your client-side scripts directly in your index.html using
<script>tags, so they run in the browser wheredocumentis available:<!-- 在index.html的<body>末尾添加 --> <script src="/client/inventory.js"></script> <script src="/client/entity.js"></script> <!-- 如果entity有客户端逻辑的话 -->Audit the
refreshRender()Function
Open inventory.js and check every use ofdocument—these lines should only run in the browser. For example, if your function looks like this:// inventory.js - 仅在浏览器运行的客户端代码 function refreshRender(inventoryData) { const inventoryElement = document.getElementById('player-inventory'); // 更新inventoryElement的内容... }This is totally safe for the browser, but it will break if executed in Node.js. Double-check that this file never gets
require()d by your server.Fix the
refreshRender()Call in entity.js
If entity.js is a server-side module, it shouldn't callrefreshRender()directly. Instead, the server should send a message to the client (via WebSockets, Socket.io, or an API endpoint) telling it to update the inventory. Here's an example:- Server-side entity.js:
// 假设用Socket.io处理实时玩家通信 function updatePlayerInventory(playerId, newInventory) { // 先更新MongoDB中的玩家数据... // 然后通知对应客户端刷新UI io.to(playerId).emit('inventoryUpdated', newInventory); } - Client-side inventory.js:
// 监听服务器的更新事件 socket.on('inventoryUpdated', (newInventory) => { // 现在处于浏览器环境,document存在,可以安全调用refreshRender refreshRender(newInventory); });
- Server-side entity.js:
Key Takeaway
Always keep server-side (Node.js) and client-side (browser) code strictly separated. Server code handles database interactions, core game logic, and client communication—never DOM manipulation. Client code handles UI updates and user input, where document and other browser APIs are available.
内容的提问来源于stack exchange,提问作者Holly Robertson

