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

部署Node.js应用至Heroku时出现‘找不到express模块’错误求助

解决Heroku部署Node.js应用时"Cannot find module 'express'"的问题

你的本地运行正常,但Heroku部署后找不到express,核心原因是依赖包的位置和Heroku的安装逻辑不匹配:

  • 所有依赖都声明在server/package.json里,但Heroku默认会在项目根目录执行npm install,而根目录的package.json没有任何依赖声明,导致express等包根本没被安装。
  • 本地运行正常是因为你在server目录下执行了npm install,依赖都装在了server/node_modules里,启动时能找到模块。

方案一:将依赖统一移到根目录package.json

这是更简洁的单包结构,适合大多数项目:

  1. 打开server/package.json,复制dependencies里的所有内容。
  2. 粘贴到根目录的package.json中,补全根目录的package.json(确保结构完整):
{
  "name": "blog-post-mongo",
  "version": "1.0.0",
  "description": "",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "develop": "concurrently \"cd server && npm run devstart\" \"cd client && npm start\""
  },
  "dependencies": {
    "bcrypt": "^5.1.0",
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "mongoose": "^6.9.1",
    "multer": "^1.4.5-lts.1",
    "nodemon": "^2.0.20",
    "path": "^0.12.7"
  }
}
  1. 删除server目录下的node_modules、package-lock.json和package.json(如果不需要保留子包结构)。
  2. 本地执行npm install重新安装依赖,然后提交代码到Heroku重新部署。

方案二:修改脚本让Heroku安装子目录依赖

如果需要保留server独立的包结构,修改根目录的package.json脚本,让Heroku处理子目录的依赖安装:

  1. 更新根目录package.json的scripts,添加heroku-postbuild脚本,并修改start脚本:
{
  "name": "blog-post-mongo",
  "version": "1.0.0",
  "description": "",
  "main": "server/server.js",
  "scripts": {
    "start": "cd server && npm start",
    "test": "echo \"Error: no test specified\" && exit 1",
    "develop": "concurrently \"cd server && npm run devstart\" \"cd client && npm start\"",
    "heroku-postbuild": "cd server && npm install"
  }
}
  1. 确保.gitignore没有忽略server/package.json和server/package-lock.json(默认不会忽略,除非你手动添加了规则)。
  2. 提交代码到Heroku,Heroku会在构建阶段执行heroku-postbuild,进入server目录安装依赖,启动时也会进入server目录执行启动命令。

额外检查项

  • 确认.gitignore中包含node_modules,避免把本地依赖包提交到仓库(Heroku会自行安装)。
  • 确保Procfile的内容web: npm start没有错误,它会触发根目录的start脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:30:37