【问题标题】:Separating logic from Express router and still access Express functions将逻辑与 Express 路由器分离,仍然可以访问 Express 功能
【发布时间】:2018-05-16 11:50:09
【问题描述】:

我已经开始使用 Node.js 和 Express 编写我的第一个应用程序,但是我的路由器文件变得非常混乱。在我看来,它包含了太多的逻辑。

我正在尝试将另一个文件 (Parent.controller.js) 中的函数传递给路由器,而不是将我的逻辑放入匿名函数中。

所以,像这样:

Router.post('/create-child', Parent.createChild);

而不是这样:

Router.post('/create-child', function(req, res, next) {
    // do something
    // do something else
    // do even more stuff
    // this is getting messy
    // oh dear
});

但我不知道如何从Parent.controller.js 中的函数触发重定向或保存闪存数据。这是因为我不确定如何仍然从Parent.controller.js 访问reqres 对象。如有任何建议,我们将不胜感激。

【问题讨论】:

    标签: javascript node.js express model-view-controller


    【解决方案1】:

    reqres 只是作为参数传递给控制器​​函数的普通对象。您不必在 Parent.controller.js 中要求任何特殊内容。只要确保createChild 的参数是reqres。如果需要,next。像这样:

    module.exports.createChild = (req, res, next) => {
       res.status(200).json({ message: 'OK' });
    }
    

    当然,您必须在路由文件中要求 express:

    const express = require('express');
    const Parent = require('Parent.controller');
    
    const router = express.Router();
    
    Router.post('/create-child', Parent.createChild);
    

    【讨论】:

      【解决方案2】:

      您可以将所有函数包装在一个对象中并像这样导出它 -

      Parent.controller.js

      function createChild(req, res, next) {
        // do your thing here
      }
      
      // Add more functions
      
      // Export module
      
      module.exports = {
        createChild,
        ... // other functions
      }
      

      然后像这样添加到路由器中 -

      const Parent = require('./Parent.controller.js');
      
      Router.post('/create-child', Parent.createChild);
      

      或者你可以走上课路线 -

      Parent.controller.js

      class Parent {
        constructor() {
          // fill constructor info
        }
      
        createChild(req, res, next) {
          // do your thing here
        }
      }
      
      module.exports = Parent;
      

      你的路由器 -

      const Parent = require('./Parent.controller.js');
      const parent = new Parent();
      
      Router.post('/create-child', parent.createChild);
      

      【讨论】:

        【解决方案3】:

        您到底尝试了什么?访问req,res 应该非常简单,

        (module.exports.)createChild = function(req,res){
            childName = req.child_name; 
            ..........
            your child genesis code
            .....
            res.send('Child created')
        }
        

        根据重定向,您可以使用res.redirect() 触发它们,但是,如果您想将用户重定向到另一个页面,我建议您将res.status(307).send 或类似的东西发送到您的前端,这将捕获状态码并触发window.assign() 或类似的东西。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-07
          • 1970-01-01
          • 1970-01-01
          • 2020-07-23
          • 1970-01-01
          相关资源
          最近更新 更多