我遇到了重构问题,我看不清楚如何解决问题:
1。此部分代码(未经过修改)可正常运行:
'use strict';
// will use svcs when refactoring
var svcs = require('../../../services/ensure-authenticated.server.service'),
config = require('../../../config/config.server.config.js'),
ctrl = require('../../../controllers/index.server.controller'),
express = require('express'),
router = express.Router();
// will remove when refactoring
var jwt = require('jwt-simple');
var moment = require('moment');
// to be refactored
function ensureAuthenticated(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send({message: 'Please make sure your request has an Authorization header'});
}
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.token_secret);
if (payload.exp <= moment().unix()) {
return res.status(401).send({message: 'Token has expired'});
}
req.user = payload.sub;
next();}
module.exports = function(app){
router.route('/me')
// middleware will change when refactored
.get(ensureAuthenticated, ctrl.userCtrl.getMe)
.put(ensureAuthenticated, ctrl.userCtrl.putMe);
app.use('/api', router);
}
2a上。但如果我重构,请确保验证:
'use strict';
var config = require('../config/config.server.config.js');
var jwt = require('jwt-simple');
var moment = require('moment');
var self = {
ensureAuthenticated: function (req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send({message: 'Please make sure your request has an Authorization header'});
}
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.TOKEN_SECRET);
if (payload.exp <= moment().unix()) {
return res.status(401).send({message: 'Token has expired'});
}
req.user = payload.sub;
next();
}
}
module.exports = self;
2B。我的路线现在看起来像这样:
'use strict';
var svcs = require('../../../services/ensure-authenticated.server.service.js'),
ctrl = require('../../../controllers/index.server.controller.js'),
express = require('express'),
router = express.Router();
module.exports = function(app, config){
router.route('/me')
.get(svcs, ctrl.userCtrl.getMe)
.put(svcs, ctrl.userCtrl.putMe);
app.use('/api', router);
}
我收到以下错误:
Error: Route.get() requires callback functions but got a [object Object]
代码至少没有改变,它只是被重构,我不明白为什么会这样。
有谁知道为什么会这样,以及如何纠正?
非常感谢。
答案 0 :(得分:0)
我的愚蠢错误:
.get(svcs.ensureAuthenticated, ctrl.userCtrl.getMe)
.put(svcs.ensureAuthenticated, ctrl.userCtrl.putMe);