我应该何时在javascript中使用require(' module')之后使用点(。)

时间:2018-06-07 05:31:51

标签: javascript

我有这个验证中间件,我导出了这个



var {User} = require('./../model/user');

var authenticate = (req, res, next) => {
    var token = req.header('x-auth');
    User.findByToken(token).then((user) => {
        if (!user) return Promise.reject();
        req.user = user;
        req.token = token;
        next();
    }).catch((err) => res.status(401).send());
}

module.exports = {authenticate};




在server.js var authenticate = require('./middleware/authenticate')中 没工作。

为什么我需要添加这个

var authenticate = require('./middleware/authenticate').authenticate;

如果我在要求之后没有添加.authenticate,则将错误记录为

  

Route.get()需要一个回调函数,但得到一个[object Object]

2 个答案:

答案 0 :(得分:1)

module.exports = {authenticate};

您正在导出对象{ authenticate: authenticate },但中间件需要一个存储在导出对象的authenticate属性中的函数,这就是.authenticate正常工作的原因。您可以仅导出该功能,例如

module.exports = authenticate;

然后你不需要一个点,用你的话说。

答案 1 :(得分:1)

模块是Javascript中代码结构的基本构建块。您可以使用它们来构建代码。 当你写

module.exports = someobject

您实际上是在为模块的客户端定义一个公共接口。

现在考虑以上基本上有两部分的陈述: - 1)有一个变量名(左手侧)
2)有一个对象。 (右手边)

您的语句只是将对象与变量名相关联。 您可以使用此语句将任何内容与变量(module.exports)相关联。

现在让我们来解决你的问题

 //authenticate.js
 // some code
 module.exports = {authenticate};  // your interface is pointing to an object

//server.js

var authenticate = require('./middleware/authenticate');

/* after this statement your module.exports is pointing to {authenticate} object which is not a callable.
You actually wants to access the the authenticate function which lies inside /this object therefore when you do*/


var authenticate = require('./middleware/authenticate').authenticate 
// it works because you are now accessing the function inside the object which is callable.