javascript - 我什么时候应该在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 中代码结构的基本构建块。您可以使用它们来构建您的代码。当你写
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.
推荐阅读
- docker - /bin/sh: 1: 语法错误:未终止的带引号的字符串
- pycharm - 使用pycharm进行机器人框架测试的目录结构
- python - 复制具有指定扩展名的文件并保留文件夹树结构
- bixby - Bixby:希望在单击按钮时重定向到 Web 浏览器 url
- python - 如何使用 Selenium 和 python 在 Tor 浏览器中单击按钮
- java - wrap_content 或 match_parent 没有给出正确的结果
- javascript - 增量运算符在这里做什么以及它如何改变比例?
- java - 搜索 CRUD 教程
- c++ - 使用数据初始化向量不起作用 - push_back() 确实有效
- html - 在 Rmarkdown 中为文本着色失败:color-text.lua 在 RevealJS 中不起作用