首页 > 解决方案 > 我什么时候应该在javascript中的require('module')之后使用点(。)

问题描述

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

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.jsvar authenticate = require('./middleware/authenticate') 中不起作用。

为什么我需要添加这个

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

如果我在 require 后不添加 .authenticate ,则会将错误记录为

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

标签: javascript

解决方案


模块是 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.

推荐阅读