Middleware.js
var _ = require('underscore');
var db = require('./mongoose.js');
var middleWareFunctions = {}; //define middleware object (cont. functions)
var authenticate = function (req, res, next) {
var token = req.header('x-auth');
db.user.findByToken(token).then((result) => {
if (!result) { //No found user.
return Promise.reject();
}
req.user = user;
req.token = token;
next(); //Otherwise the other route won't run.
///The above req gets passed in to main route (this is the middle-ware).
}).catch((e) => {
res.status(401).send();
});
};
middleWareFunctions.authenticate = authenticate;
module.exports = middleWareFunctions;
server.js
var {authenticate} = require('Middleware.js');
这准确吗?我在我的实际路线中使用它作为我的中间件,它似乎不起作用。我该如何引用这个对象?
我想检索authenticate
对象内的middleWareFunctions
函数。
答案 0 :(得分:0)
export function authenticate (req, res, next) {
var token = req.header('x-auth');
db.user.findByToken(token).then((result) => {
if (!result) { //No found user.
return Promise.reject();
}
req.user = user;
req.token = token;
next(); //Otherwise the other route won't run.
///The above req gets passed in to main route (this is the middle-ware).
}).catch((e) => {
res.status(401).send();
});
}
你尝试过这样的事吗?
您可以导出任意数量的对象/函数,并在其他文件中访问它们
import { authenticate } from 'middleware';
如果您导出类似
的内容 export default function auth() {}
你会得到它
imoort auth from 'middleware'