NodeJS Express服务器在CPanel部署后启动失败求助
问题描述
使用CPanel部署基于NodeJS v16.17.1、集成DiscordJS与Express的服务器到cdnapi.club时,服务器监听端口3000后随即崩溃,报错如下:
Listening on port 3000 stderr: /home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184 if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { ^ TypeError: Cannot read properties of undefined (reading 'timeoutType') at _resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184:29) at resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1148:3) at connect (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1133:3)
当前启动文件index.js内容:
const express = require('express'); const app = express(); const port = 3000 app.set('port', port) const v1_path = "/api/v1" app.listen(port, () => { console.log(`Listening on port ${port}`) }) app.get(`/`, (request, response) => { response.sendFile(__dirname + '/pages/index.html') })
package.json依赖包含discord.js@14.11.0、express@4.18.2等,核心问题为discord.js依赖的undici版本与NodeJS v16存在兼容性冲突。
解决方案
1. 锁定兼容的undici版本
在package.json中添加resolutions字段,强制指定undici为兼容NodeJS v16的版本(如5.22.1):
"resolutions": { "undici": "5.22.1" }
若使用npm,需安装npm-force-resolutions作为开发依赖,并添加预处理命令确保生效:
"devDependencies": { "npm-force-resolutions": "^0.0.10" }, "scripts": { "preinstall": "npx npm-force-resolutions" }
执行上述配置后,重新运行npm install。
2. 升级NodeJS版本
如果CPanel支持,将NodeJS版本升级至v18及以上。新版本NodeJS对undici的兼容性更完善,可直接解决该报错。
3. 调整CPanel端口配置
CPanel通常会分配指定端口而非允许自定义3000,修改index.js中的端口获取逻辑,适配平台分配的端口:
const port = process.env.PORT || 3000; app.set('port', port);
同时确认CPanel中NodeJS应用的启动命令正确指向index.js。
内容的提问来源于stack exchange,提问作者cdnAshton
相关产品推荐
相关产品推荐

