NodeJS error: internal/modules/cjs/loader.js:905-Cannot find module './config'

NodeJS error: internal/modules/cjs/loader.js:905-Cannot find module './config'

我的节点应用程序出现以下控制台错误:Error: Cannot find module './config'

我已经阅读了类似的问题(例如 ),所以我检查了重复的 folder/file 名称,但我会遗漏什么吗?

下面是我在执行“node app.js”命令后在控制台中遇到的完整错误。

internal/modules/cjs/loader.js:905
  throw err;  
  ^

Error: Cannot find module './config'
Require stack:
- C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\config\db.js
- C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\app.js
  at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
  at Function.Module._load (internal/modules/cjs/loader.js:746:27)
  at Module.require (internal/modules/cjs/loader.js:974:19)
  at require (internal/modules/cjs/helpers.js:92:18)
  at Object.<anonymous (C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\config\db.js:2:16)
  at Module._compile (internal/modules/cjs/loader.js:1085:14)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
  at Module.load (internal/modules/cjs/loader.js:950:32)
  at Function.Module._load (internal/modules/cjs/loader.js:790:14)
  at Module.require (internal/modules/cjs/loader.js:974:19)
  at require (internal/modules/cjs/helpers.js:92:18)
  at Object.<anonymous> (C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\app.js:2:19)
  at Module._compile (internal/modules/cjs/loader.js:1085:14)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
  at Module.load (internal/modules/cjs/loader.js:950:32)
  at Function.Module._load (internal/modules/cjs/loader.js:790:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\config\db.js',
'C:\Users\arthu\development\projectWhereWoof\dustyv3\backend\app.js'
  ]
}

下面是我的文件夹结构和代码,我是 运行。


//app.js
const express = require('express');
const connectDB = require('./config/db');
var cors = require('cors');
// routes
const dogs = require('./routes/dogs');
const app = express();
// Connect Database
connectDB();
// cors handling logic
app.use(cors({ origin: true, credentials: true }));
// Init Middleware
app.use(express.json({ extended: false }));
app.get('/', (req, res) => res.send('Hello world!'));
// use Routes
app.use('./routes/dogs', dogs);
const port = process.env.PORT || 8082;
app.listen(port, () => console.log(`Server running on port ${port}`));

//db.js
const mongoose = require('mongoose');
const config = require('./config');
const db = config.get('mongoURI');

const connectDB = async () => {
   try {
     await mongoose.connect(
       db,
       {
         useNewUrlParser: true,
         useUnifiedTopology: true 
       }
    );

    console.log('MongoDB is Connected...');
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};
module.exports = connectDB;

//default.json
{
"mongoURI":
  "mongodb+srv://INTENTOMITTED:INTENTOMITTED@INTENTOMITTED.oxagu.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
}

//Dogs.js
const mongoose = require('mongoose');
const DogSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  breedTypePrim: {
    type: String,
    required: true
  },
  breedTypeSec: {
    type: String,
    required: false
  },
  birthday: {
    type: Date,
    required: false
  },
  adoptionDate: {
    type: Date,
    required: true
    },
  weight: {
      type: Number,
      required: false
    },
  origin: {
    type: String,
    required: false
  }
});

module.exports = Dog = mongoose.model('dog', DogSchema);

//dogs.js
const express = require('express');
const router = express.Router();

// Load Dog model
const Dog = require('../models/Dogs');

// @route GET api/dogs/test
// @description tests dogs route
// @access Public
router.get('/test', (req, res) => res.send('dog route testing!'));

// @route GET api/dogs
// @description Get all dogs
// @access Public
router.get('/', (req, res) => {
  Dog.find()
    .then(dogs => res.json(dogs))
    .catch(err => res.status(404).json({ nodogsfound: 'No Dogs found' }));
});

// @route GET api/dogs/:id
// @description Get single dog by id
// @access Public
router.get('/:id', (req, res) => {
  Dog.findById(req.params.id)
    .then(dog => res.json(dog))
    .catch(err => res.status(404).json({ nodogfound: 'No Dog found' }));
});

// @route GET api/dogs
// @description add/save dog
// @access Public
router.post('/', (req, res) => {
  Dog.create(req.body)
    .then(dog => res.json({ msg: 'Dog added successfully' }))
    .catch(err => res.status(400).json({ error: 'Unable to add this dog' }));
});

// @route GET api/dogs/:id
// @description Update dog
// @access Public
router.put('/:id', (req, res) => {
  Dog.findByIdAndUpdate(req.params.id, req.body)
    .then(dog => res.json({ msg: 'Updated successfully' }))
    .catch(err =>
      res.status(400).json({ error: 'Unable to update the Database' })
    );
});

// @route GET api/dogs/:id
// @description Delete dog by id
// @access Public
router.delete('/:id', (req, res) => {
  Dog.findByIdAndRemove(req.params.id, req.body)
    .then(dog => res.json({ mgs: 'Dog entry deleted successfully' }))
    .catch(err => res.status(404).json({ error: 'No such a dog' }));
});

module.exports = router;

db.js 文件中你有 const config = require('./config');,系统将在 db.js 文件的同一文件夹中搜索 config.js 文件,该文件不可用,因此错误。

要读取default.json文件并获取mongodb连接字符串,可以这样试试:

const config = require('./default.json'); // config is a javascript object
const db = config.mongoURI;