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

index.js模块找不到问题求助:Node.js项目启动报错

启动Node.js项目时出现「Cannot find module」错误无法修复

启动Node.js项目时碰到「Cannot find module in index.js」错误,尝试解决后仍无法修复。

我的index.js代码

import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";

const app = express();
dotenv.config();
const connect = async () => {
    try {
      await mongoose.connect(process.env.MONGO);
      console.log("Connected to mongoDB.");
    } catch (error) {
      throw error;
    }
  };
  mongoose.connection.on("disconnected", () => {
    console.log("mongoDB disconnected!");
  });

  app.listen(3000, () => {
    connect();
    console.log("Connected to backend.");
  });

我的package.json代码

{
  "name": "quiz-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.2",
    "express": "^4.18.1",
    "mongoose": "^6.5.4"
  },
  "devDependencies": {
    "webpack-cli": "^3.3.12"
  }
}

错误详情

运行项目时的错误提示为:Error: Cannot find module 'express',报错指向index.js的第一行import express from "express";


解决步骤

  • 重新安装依赖:执行命令 npm install,确保所有声明的依赖包都正确安装到node_modules目录
  • 检查Node.js版本:当前依赖包要求Node.js 14.x及以上版本,用node -v查看版本,版本过低则升级Node.js
  • 启用ES模块支持:在package.json中添加"type": "module"字段,与"main": "index.js"同级——Node.js默认使用CommonJS模块规范,而你的代码用了ES模块的import语法,必须显式声明启用
  • 清理缓存重装:如果安装存在异常,先删除node_modules和package-lock.json(Windows:rmdir /s /q node_modules && del package-lock.json;Mac/Linux:rm -rf node_modules package-lock.json),再执行npm install

内容的提问来源于stack exchange,提问作者Arif Shahriyar Nader

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:21:31