简体   繁体   English

module.exports与对象

[英]module.exports with object

I'm starting with node.js and javascript server side. 我从node.js和javascript服务器端开始。 I think, maybe I got confused with the module.exports thing. 我认为,也许我对module.exports感到困惑。 And I'm pretty sure it's a noob issue. 而且我很确定这是菜鸟问题。

I'm trying to do a simple task : 我正在尝试做一个简单的任务:

oAuth - controler [oAuth.js] oAuth-控制器[oAuth.js]

  module.exports = function() {
  return {
    tryLogin :function(Username,Password){

   }
  };
}

oAuth - dispatcher [route.js] oAuth-调度程序[route.js]

module.exports = function(app){


    app.post('/api/oAuth/login', function(req, res){
        console.log("Trying to log with :");
        console.log(req.body.Username);
        console.log(req.body.Password);


        var oAuthCtrl = require('./oAuth.js');
        var result = oAuthCtrl.tryLogin(req.body.Username,req.body.Password);
        res.send(result);

    });
}

And the console result is : 控制台结果是:

TypeError: Object function (width) {
  return {
    tryLogin :function(Username,Password){

   }
  };
} has no method 'tryLogin'

What I want is an oAuth object inside my oAuthCtrl variable. 我想要的是我的oAuthCtrl变量内的oAuth对象。 This way I'll be able to call my tryLogin method. 这样,我就可以调用我的tryLogin方法。

The end point here is to build an oAuth module using passeport.js with some block and page views and methods like register, tryLogin, logout etc... 此处的终点是使用passeport.js并使用一些块和页面视图以及方法(例如注册,tryLogin,注销等)来构建oAuth模块。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You don't need to wrap tryLogin in an anonymous function when you export it. 导出tryLogin ,无需将其包装在匿名函数中。

Simply put, module.exports is an object. 简而言之, module.exports 一个对象。 You could almost think of it as a sort of "return value" from calling require on a script. 通过在脚本上调用require ,您几乎可以将其视为一种“返回值”。

You just want 你只想要

// oauth.js
function tryLogin {
  // ...
}

module.exports.tryLogin = tryLogin;

Here's an alternative based on your comment 这是根据您的评论选择的

// oauth.js
function MyClass() {

}

MyClass.tryLogin = function tryLogin() {
  // ...
};

module.exports = MyClass;

In the last line, we're effectively replacing the default empty object provided by module.exports with our "class". 在最后一行,我们有效地 module.exports提供的默认空对象替换为我们的“类”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM