【问题标题】:Node, Express - Index file not calling files correctlyNode、Express - 索引文件未正确调用文件
【发布时间】:2020-05-05 17:19:11
【问题描述】:

嗨,在我的 express 项目中,我有我的索引文件,我需要不同的文件来启动我的应用程序。这些需要一个数据库连接文件、一个用于使用 winston 记录内容的文件以及一个用于配置路由的文件。

我使用 express 中的require() 语句来调用这些文件,并且当我运行应用程序(使用 nodemon)时,我希望将一些消息记录到终端以验证文件已被调用,但是没有消息出现.

这是我的代码: index.js

const express = require('express')
const app = express()

require('./startup/logging') ()
require('./startup/db') ()
require('./startup/routes') (app)

const port = process.env.PORT || 3000
app.listen(port, () => winston.info(`Listening on port: ${port}`))

db.js:

const mongoose = require('mongoose')
const winston = require('winston')

module.exports = function() {

    mongoose.connect('mongodb://localhost/dwg', {useNewUrlParser: true, useUnifiedTopology: true})
        .then(() => winston.info('Connected to MongoDB...'))
        .catch(err => console.error("Error"))
}

logging.js

const winston = require('winston');

    module.exports = function() {
      winston.handleExceptions(
        new winston.transports.File({ filename: 'uncaughtExceptions.log' }));

      process.on('unhandledRejection', (ex) => {
        throw ex;
      });

      winston.add(winston.transports.File, { filename: 'logfile.log' });
    }

routes.js

const express = require('express');

module.exports = function(app) {
    app.use(express.json())
}

运行应用程序时未创建数据库。我可以通过查看 mongodb 指南针来确认这一点。由app.listen() 打印的消息也不会打印到控制台。有人知道这个问题吗?谢谢。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    这样做的问题是您的应用程序在有机会完成其余工作(如创建数据库连接等)之前启动。您应该仅在完成这些任务后启动应用程序。像这样的

    const express = require('express')
    const app = express()
    
    const logging = require('./startup/logging');
    const db = require('./startup/db');
    const routes = require('./startup/routes');
    
    const port = process.env.PORT || 3000
    app.listen(port, async () => {
      await logging();
      await db();
      await routes();
      // assuming you have winston here.
      winston.info(`Listening on port: ${port}`)
    })
    
    Mongo part is defintely async so need await. Check if routes and logging needs await or not.
    
    

    【讨论】:

    • 你好。 db 连接的消息被打印到控制台,但实际上并没有创建数据库。你知道为什么吗?谢谢。
    • connect 命令不应该连接数据库。您需要创建数据库。集合是自己创建的。
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多