代码之家  ›  专栏  ›  技术社区  ›  gremo

有没有一种“标准”的方法来组织/引导express.js服务器?

  •  0
  • gremo  · 技术社区  · 8 年前

    我对node.js和javascript还很陌生,它来自php环境。

    我面临着以下问题:许多php框架自己做一些“繁重”的事情来提升应用程序(即设置服务器、中间层、日志、整合)。

    在Express中,我是在一个 app.ts (typescript示例):

    // Create schema and load configurations
    import config from './config';
    
    // Configure and load the logger
    import logger from './logger';
    
    // Create the Express.js server
    // ...
    
    // Configure global middlewares
    app.use(morgan('tiny'));
    app.use(compression());
    app.use('/', express.static(`${__dirname}/../public`));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // Configure global routing
    app.get('/', (req, res) => {
      res.sendFile(`${__dirname}/../public/index.html`);
    });
    
    // Establish a connection to the database server
    createConnection({
      // options
    }).then(() => {    
      // Start the web server
      app.listen(/* options */);
    });
    

    这个文件(这是一部分)太大了,我想拆分它。在节点生态系统中,有什么“标准”的方法可以做到这一点吗?

    以下方法有意义吗?

    import * as express from 'express';
    import config from './config';
    import { Connection } from 'typeorm';
    
    export class ServerConfigurer {
      configureApp(app): void {
        // Configure global middlewares
      }
      createConnection(): Promise<Connection> {
        // Create MySQL connection
      }
    }
    

    …然后在我的 阿普茨 使用 ServerConfigurer 类来启动应用程序。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Cisco    8 年前

    在Express中,我是在一个 app.ts

    几乎所有的微结构都是这样,特别是express。没有正确或错误的方法来组织你的项目。

    有没有一种标准的方法来组织/引导express.js服务器?

    典型地 ,下面是许多示例 MVC 模式。例如,您通常会发现布局如下:

    example
    ├── app.js
    ├── controllers/
    ├── models/
    ├── routes/
    ├── public/
    └── views/
    

    然而,express主要用于构建api。现在的前端( views/ public/ 文件夹) 典型地 React、Vue或Angular应用程序是它自己的项目, 分离 从你的express api。这么说吧,一个 典型的 express api项目布局为:

    example
    ├── app.js
    ├── controllers/
    ├── models/
    └── routes/
    

    app.js 是所有初始化的地方。通过初始化,我的意思是安装路由、中间件、数据库连接、事件侦听器……任何真正的东西。 App.JS 是您的Express应用程序的主要/第一个入口点。

    models/ 是定义所有数据库模型的位置( 典型地 Mongo)例如:

    // models/contact.js
    const mongoose = require('mongoose');
    
    const definition = {
      name: {
        type: String,
        trim: true,
        required: true,
      }
    };
    
    const schema = new mongoose.Schema(definition, { timestamps: true });
    
    module.exports = mongoose.model('Contact', schema);
    

    controllers/ 是所有路由处理程序都要去的地方。例如:

    // controllers/contact.js
    const Contact = require('../models/contact');
    
    exports.index = async (req, res) => {
      const contacts = await Contact.find().exec();
      res.json({
        status: 200,
        data: contacts,
      });
    };
    

    我们终于有了 routes/ 这是定义所有路由和安装/映射控制器的位置。例如:

    // routes/contact.js
    const express = require('express');
    const contactController = require('../controllers/contact');
    
    const router = express.Router();
    
    router.get('/', contactController.index);
    
    module.exports = router;
    

    最后,我们需要把一切联系起来:

    const express = require('express');
    const mongoose = require('mongoose');
    const contactRoutes = require('./routes/contact');
    
    const app = express();
    
    // Connect to mongo.
    mongoose.connect(process.env.MONGO_URI);
    
    // Fail on connection error since we need the database.
    mongoose.connection.on('error', error => { throw error; });
    
    // Allows parsing the body content via `req.body`
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    
    // Mount API routes.
    app.use('/contacts', contactRoutes);
    
    app.listen(process.env.NODE_PORT, () => console.log(`Listening on ${process.env.NODE_PORT}`))
    
    推荐文章