【问题标题】:How to use module in my own node js module?如何在我自己的节点 js 模块中使用模块?
【发布时间】:2020-11-19 22:00:15
【问题描述】:

我如何使用自己的第三方模块?例如,如果我在应用程序主文件中有类似(使用 body-parser):

app.post("/dothis", (req,res)=>{
    var name = req.body.name;
    console.log(name);
};

这很好。但是当我想把它放在单独的文件中(例如 mod.js),并这样写:

exports.own = function(){
       var name = req.body.name;
       console.log(name);
}

然后在主文件中写道:

const mod = require(__dirname + "/mod.js")



app.post("/dothis", (req,res)=>{
        mod.own();
    };

然后我得到错误,req is undefined。

我正在尝试添加 mod.js 文件

const {req} = require ("http");

然后我得到了无法读取未定义名称的值的错误。

有一个问题,我如何将使用 body-parser、express 和其他模块的代码转移到单独的文件或创建自己的模块以获取工作模块?

谢谢!

【问题讨论】:

    标签: node.js module body-parser


    【解决方案1】:

    因为你没有通过请求,所以你变得不确定。

    看看你的代码,试试这个。

    exports.own = function(req){ // use request
           var name = req.body.name;
           console.log(name);
    }
    
    const mod = require(__dirname + "/mod.js")
    
    
    
    app.post("/dothis", (req,res)=>{
            mod.own(req); // pass request
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多