我有这个身份验证中间件,并且我导出了这个
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 中varauthenticate = require('./middleware/authenticate')
没用。
为什么我需要添加这个
var verify = require('./middleware/authenticate').authenticate;
如果我在 require 之后没有添加 .authenticate ,则会将错误记录为
Route.get() requires a callback function but got a [object Object]
模块是 Javascript 代码结构的基本构建 block 。您可以使用它们来构建您的代码。当你写
module.exports = someobject
您实际上是在为模块的客户端定义一个公共(public)接口(interface)。
现在考虑上面的陈述,它基本上有两个部分:-
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.
Tôi là một lập trình viên xuất sắc, rất giỏi!