我在一个现有的项目中工作,我有一个让我疯狂的问题:
路由被调用两次或者甚至更多,这种情况发生在任何被调用的路由需要太长时间才能响应
我认为问题出在此文件中,即动态路由尝试
var express = require('express');
var recaptcha = require('express-recaptcha');
//Site key, Secret key
recaptcha.init('xxxxx', 'yyyyy');
/**
* Routes middleware
* Check all requests
*/
module.exports = function(app, passport, memoryCache) {
var router = express.Router();
var config = require('app/config/settings.js');
router.use(function(req, res, next) {
console.log("touch");
console.log(req.url);
/**
* Make visible req / res on template layout
*/
res.locals.req = req;
res.locals.res = res;
/**
* Url filter
*/
var aryUrl = req.path.split('/').filter(Boolean);
try {
var root = '';
var controller = '';
var controllerPrototype = '';
var module = '';
var method = '';
var url = '';
var itemId = '';
var privacity = '';
var session = '';
switch (req.originalMethod) {
case 'GET':
method = 'get';
break;
case 'POST':
method = 'post';
break;
case 'PUT':
method = 'put';
break;
case 'DELETE':
method = 'delete';
break;
}
if (aryUrl.length == 0) {
root = '/';
} else {
root = aryUrl[0];
}
switch (root) {
case '/':
privacity = 'private';
session = 'General';
module = 'app/controllers/indexController';
controller = 'index';
controllerPrototype = 'root';
url = '/';
break;
case 'index':
privacity = 'private';
session = 'General';
module = 'app/controllers/indexController';
controller = 'index';
controllerPrototype = aryUrl[1];
url = '/index/' + aryUrl[1];
break;
case 'evaluaciones':
privacity = 'private';
session = 'PortalEval';
module = 'app/controllers/view-private/portalEvaluacionController';
controller = 'portalEvaluacion';
controllerPrototype = 'view';
url = '/evaluaciones';
if (aryUrl.length == 2) {
if (aryUrl[1] === 'antesdelcurso' || aryUrl[1] === 'despuesdelcurso') {
url = url + '/' + aryUrl[1];
} else {
controller = '';
}
}
break;
case 'relatores':
privacity = 'private';
session = 'RelatorEval';
module = 'app/controllers/portalRelatoresIndexController';
controller = 'portalRelatores';
controllerPrototype = 'view';
url = '/relatores';
break;
case 'api-pc':
privacity = 'public';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
module = 'app/controllers/api-public/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/api-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'api-pt':
privacity = 'private';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);
module = 'app/controllers/api-private/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/api-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'view-pc':
privacity = 'public';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
module = 'app/controllers/view-public/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/view-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'view-pt':
privacity = 'private';
session = (req.user)? req.user.tipoSession : '';
var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
return chr.toUpperCase();
});
module = 'app/controllers/view-private/' + ctrl + 'Controller';
controller = ctrl;
if (aryUrl.length == 4) {
itemId = '/:id';
}
controllerPrototype = aryUrl[2];
url = '/view-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;
break;
case 'auth':
/**
* Local Login
*/
var successGetLog = function(req, res) {
res.render('login/get.html', {
layout: 'layout/auth.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
loginAttempts: req.flash('loginAttempts')
});
};
var successPostLog = function (req, res) {
var loginAttempts = res.locals.req.user.loginAttempts;
if (loginAttempts >= 4){
recaptcha.verify(req, function(error){
if(error){ //Falla de verificacion de captcha
res.render('login/get.html', {
layout: 'layout/auth.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
loginAttempts: loginAttempts,
captcha:recaptcha.render()
});
} else { //Exito de verificacion de captcha
res.redirect('/');
}
});
} else {
res.redirect('/');
}
};
var successGetLogout = function(req, res) {
req.logout();
res.redirect('/');
};
router.route('/auth/login').get(successGetLog);
router.route('/auth/login').post(passport.authenticate("local-login", {failureRedirect: '/auth/logout'}), successPostLog);
router.route('/auth/logout').get(successGetLogout);
/**
* Encuesta Local Login
*/
var successGetPortalLog = function(req, res) {
if (req.query.rut != undefined || req.query.token == 'bciboost') {
if (req.query.rut != undefined && req.query.token == 'bciboost') {
console.log('casi');
req.body = {
rut: req.query.rut,
password: 'null'
};
passport.authenticate('portaleval-link-login', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
if (user) {
res.redirect('/evaluaciones');
}
});
})(req, res, next);
} else {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: 'Existe un problema al iniciar sesión',
access: req.path,
});
}
} else {
if (Object.keys(req.session.passport).length !== 0 && req.session.passport.constructor === Object && req.path === '/auth/evaluaciones' && req.session.passport.user.type === 'PortalEval') {
res.redirect('/evaluaciones');
} else {
res.render('portalevaluacionapp/portal_evaluacion_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
};
}
}
var successPostPortalLog = function(req, res) {
res.redirect(req.path.replace('/auth', ''));
};
var successGetPortalLogout = function(req, res) {
req.logout();
res.redirect(req.path.replace('/logout', ''));
};
var successGetPortalRelatorLogout = function(req, res) {
req.logout();
res.redirect("/auth/relatores");
};
if (req.path === '/auth/evaluaciones' || req.path === '/auth/evaluaciones/antesdelcurso' || req.path === '/auth/evaluaciones/despuesdelcurso') {
var rutAux = req.body.rut;
req.body = {
rut: (typeof rutAux === 'undefined' || rutAux === '')? 'null': req.body.rut,
password: 'null'
};
}
router.route('/auth/evaluaciones').get(successGetPortalLog);
router.route('/auth/evaluaciones/antesdelcurso').get(successGetPortalLog);
router.route('/auth/evaluaciones/despuesdelcurso').get(successGetPortalLog);
router.route('/auth/evaluaciones').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/antesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/despuesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
router.route('/auth/evaluaciones/logout').get(successGetPortalLogout);
router.route('/auth/evaluaciones/logout/antesdelcurso').get(successGetPortalLogout);
router.route('/auth/evaluaciones/logout/despuesdelcurso').get(successGetPortalLogout);
var successGetRelatorLog = function(req, res) {
res.render('portalrelatoresapp/portal_relatores_login.html', {
layout: 'layout/empty.html',
entorno: config.config_entorno.empresa,
message: req.flash('loginMessage'),
access: req.path,
});
};
var successPostRelatorPortalLog = function(req, res) {
res.redirect(req.path.replace('/auth', ''));
};
router.route('/auth/relatores').get(successGetRelatorLog);
router.route('/auth/relatores').post(passport.authenticate("portalrelatores-login", {failureRedirect: '/auth/relatores'}), successPostPortalLog);
router.route('/auth/relatores/logout').get(successGetPortalRelatorLogout);
break;
default:
break;
}
if (controller != '') {
var controllerDynamic = require(module);
controllerDynamic.req = req;
controllerDynamic.res = res;
/**
* Auth validation
*/
if (privacity == 'private') {
if (req.isAuthenticated()) {
if (session == 'General') {
if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
var err = new Error(402);
throw err;
}
} else
if (session == 'PortalEval') {
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
}
} else
if (session == 'RelatorEval') {
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
}
}
//==============================================================================
else
if (session == 'PortalRelator') {
if (controllerDynamic.auth.indexOf('PortalRelator') == -1) {
var err = new Error(402);
throw err;
}
}
//==============================================================================
else {
var err = new Error(404);
throw err;
}
} else {
if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
var err = new Error(402);
throw err;
} else
if (controllerDynamic.auth.indexOf('General') != -1) {
var err = new Error(401);
throw err;
} else {
var err = new Error(404);
throw err;
}
}
}
/**
* Check the "auth" atribute of a controller
*/
// if (controllerDynamic.auth.indexOf(controllerPrototype) != -1) {
// }
/**
* Final validation
*/
var isValid = true;
if (aryUrl.length > 4) {
isValid = false;
}
if (method == '') {
isValid = false;
}
if (typeof controllerDynamic[controllerPrototype] !== "function") {
isValid = false;
}
if (isValid) {
router.route(url)[method](function(ctrlReq, ctrlRes){
controllerDynamic[controllerPrototype](ctrlReq, ctrlRes);
});
} else {
res.status(404).send('Not found');
}
}
next();
} catch (e) {
if (e.message == 401) {
res.status(401).redirect('/auth/login');
} else
if (e.message == 402) {
res.status(401).redirect('/auth' + url);
} else {
res.status(404).send('Not found 2');
}
}
});
app.use('/', router);
};
事实上,如果路由没有快速响应(在不到8分钟内),我会调用两次console.log(touch),我不知道发生了什么
谢谢你们!