我正在开发一个全栈项目,使用 Express.js 作为后端,使用 MongoDB 作为数据库。我在尝试启动服务器时遇到错误。错误信息如下:
Error: Cannot find module '../controllers/userController'
Require stack:
- D:\comun\dev_project\eHub\server\src\routes\userRoutes.js
- D:\comun\dev_project\eHub\server\src\app.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
at Module._load (node:internal/modules/cjs/loader:985:27)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at Object.<anonymous> (D:\comun\dev_project\eHub\server\src\routes\userRoutes.js:3:24)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Module.require (node:internal/modules/cjs/loader:1235:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'D:\\comun\\dev_project\\eHub\\server\\src\\routes\\userRoutes.js',
'D:\\comun\\dev_project\\eHub\\server\\src\\app.js'
]
}
这是我的项目结构:
server/
├── src/
│ ├── app.js
│ ├── controllers/
│ │ └── userController.js
│ ├── models/
│ │ └── User.js
│ ├── routes/
│ │ └── userRoutes.js
│ ├── services/
│ └── .env
├── package.json
src/app.js
:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// Load environment variables from .env file
dotenv.config();
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
.catch((err) => console.error(err));
const app = express();
// Middleware
app.use(express.json());
// Routes
app.use('/api/users', require('./routes/userRoutes'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
src/routes/userRoutes.js
:
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
router.post('/', userController.createUser);
router.get('/', userController.getUsers);
module.exports = router;
src/controllers/userController.js
:
const User = require('../models/User');
exports.createUser = async (req, res) => {
const { name, email, password } = req.body;
try {
const newUser = new User({ name, email, password });
await newUser.save();
res.status(201).json(newUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
exports.getUsers = async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {[enter image description here](https://i.sstatic.net/z116ogK5.png)
res.status(500).json({ error: error.message });
}
};
src/models/User.js
:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
module.exports = mongoose.model('User', UserSchema);
我已经仔细检查了文件路径和名称以确保没有拼写错误。尽管如此,我仍然收到“找不到模块”错误。
任何解决此问题的帮助将不胜感激。谢谢!:) 屏幕短
我已经仔细检查了文件路径和名称以确保没有拼写错误。尽管如此,我仍然收到“找不到模块”错误。
您可以尝试将
.js
添加到导入的后面,如下所示:
const userController = require('../controllers/userController.js');
如果这不起作用,您可以尝试在控制器文件夹中创建一个不同名称的新文件,然后将
userController.js
的内容复制到其中。使用新文件,看看是否有帮助。