【问题标题】:How can I separate a code in two files, and still make it work in node.js?如何将两个文件中的代码分开,并且仍然可以在 node.js 中工作?
【发布时间】:2015-02-18 15:05:48
【问题描述】:

(NODE.JS)

我有以下html表单:

<form class="options-form" role="form" id="form" method="post" action="/">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">

        <label for="email">Email:</label>
        <input type="text" id="email" name="email">
</form>

我想发送一条确认消息,为此我正在使用 Sendgrid - https://sendgrid.com

我已经编写了代码,并且正在 100% 工作。

代码如下:

我的路由.js

var express = require('express');
var router = express.Router();
var auth = require('../authentication/sendgrid');
var sendgrid = require('sendgrid')(auth.sg.username, auth.sg.password);


 router.get('/', function(req, res) {
   res.render('index');
 });

  router.post('/', function(req, res) {
     sendgrid.send({
                to:         req.body.email,
                from:       "confirmation@mycompany.com",
                subject:    "Confirmation email"
                html:       "some html for the body email",
        },
        function(err, json) {
            if (err) {
                return console.error(err);
            }
            console.log(json);
    });
 });

module.exports = router;

现在我想将此代码分隔在两个文件中,路由和 sendgrid.. 例如:

ROUTE.JS:

router.post('/', function(req, res) {
    something here that make the sendgrid send the email.
});

sendGrid.js

     sendgrid.send({
                to:         req.body.email,
                from:       "confirmation@mycompany.com",
                subject:    "Confirmation email"
                html:       "some html for the body email",
        },
        function(err, json) {
            if (err) {
                return console.error(err);
            }
            console.log(json);
    });

我不知道该怎么做,我的个人组织需要这个,我讨厌我的应用程序中的这种代码混乱,也用于维护。请问有人吗?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    在您的 sendGrid.js 文件中,定义以下辅助函数:

    var sendgrid = require('sendgrid');
    
    module.exports.send = function(email) {
      sendgrid.send({
        to: email,
        from: 'confirmation@mycompany.com',
        subject: 'confirmation email',
        html: 'some html',
      }, function(err, json) {
        if (err) {
          return console.error(err);
        } else {
          console.log(json);
        }
      });
    };
    

    然后,在您的 routes.js 中,像这样导入并使用您的 sendGrid.js 模块:

    var express = require('express');
    var sendGrid = require('./sendGrid');
    
    var router = express.Router();
    
    router.post('/', function(req, res) {
      sendGrid.send(req.body.email);  // this is a call to your helper function defined in the other file
    });
    

    在 Node 中,通过定义导出函数来“模块化”您的代码非常容易 =)

    【讨论】:

    • 谢谢@rdegges..你的回答很完美!!!我的 router.post 中有其他代码,现在我可以对两件事使用相同的方法!非常感谢
    • 乐于助人。尽情享受您的项目吧!
    【解决方案2】:
    1. 创建一个新文件(可能类似于 SendgridHandler.js
    2. 使该文件导出一个以路由器为参数的函数
    3. 将将 sendgrid 处理程序附加到路由器的逻辑添加到该函数中
    4. require 你的新模块,并将它传递给你的路由器

    SendgridHandler.js

    module.exports = function(router) {
        router.post('/', function(req, res){
            sendgrid.send({
                to:         req.body.email,
                from:       "confirmation@mycompany.com",
                subject:    "Confirmation email"
                html:       "some html for the body email",
            }, function(err, json) {
                if (err) {
                    return console.error(err);
                }
                console.log(json);
            });
        });
    };
    

    Index.js

    var router = express.Router();
    ...
    var SendgridHandler = require('./SendgridHandler');
    SendgridHandler(router);
    

    【讨论】:

    • 我还建议您查看我的另一个答案,以更好地了解模块化如何与 node.js 应用程序一起工作 - stackoverflow.com/questions/21831119/…
    • 非常感谢乔丹的帮助。你的答案很好,但我需要将 router.post 留在我的 routes.js 中,因为我里面还有其他代码.. 我会检查你的其他答案。
    • 很高兴我能帮上点忙。听起来这里的其他两个答案更适合您想要的模式,所以一定要采用其中一种方法。一旦您对如何使用 module.exports 和 require 有了更好的理解,您将能够在整个应用程序中使用各种模式!祝你好运:)
    【解决方案3】:

    route.js

    var sg = require('sendGrid.js');
    router.post('/', function(req, res) {
        sg.send(req, res);
    });
    

    sendGrid.js

    var auth = require('../authentication/sendgrid');
    var sendgrid = require('sendgrid')(auth.sg.username, auth.sg.password);
    
    var sg = {
        send: send;
    }
    
    function send(req, res) {
        sendgrid.send({
            to:         req.body.email,
            from:       "confirmation@mycompany.com",
            subject:    "Confirmation email"
            html:       "some html for the body email",
        },
        function(err, json) {
            if (err) {
                return console.error(err);
            }
            console.log(json);
        });
    }
    
    module.exports = sg;
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 2016-10-07
      • 1970-01-01
      • 2021-12-29
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多