From dee77c459a929d7e0041fae38176b71248a9ff9c Mon Sep 17 00:00:00 2001 From: BoHong Li Date: Wed, 12 Apr 2017 05:30:04 +0800 Subject: [PATCH] refactor(app.js): Extract middleware to module extract check URi is valid, redirect without trailing slashes --- app.js | 22 ++----------------- lib/web/middleware/checkURiValid.js | 14 ++++++++++++ .../redirectWithoutTrailingSlashes.js | 17 ++++++++++++++ 3 files changed, 33 insertions(+), 20 deletions(-) create mode 100644 lib/web/middleware/checkURiValid.js create mode 100644 lib/web/middleware/redirectWithoutTrailingSlashes.js diff --git a/app.js b/app.js index 0f59859..c18e01f 100644 --- a/app.js +++ b/app.js @@ -192,28 +192,10 @@ passport.deserializeUser(function (id, done) { }) // check uri is valid before going further -app.use(function (req, res, next) { - try { - decodeURIComponent(req.path) - } catch (err) { - logger.error(err) - return response.errorBadRequest(res) - } - next() -}) +app.use(require('./lib/web/middleware/checkURiValid')) // redirect url without trailing slashes -app.use(function (req, res, next) { - if (req.method === 'GET' && req.path.substr(-1) === '/' && req.path.length > 1) { - var query = req.url.slice(req.path.length) - var urlpath = req.path.slice(0, -1) - var serverurl = config.serverurl - if (config.urlpath) serverurl = serverurl.slice(0, -(config.urlpath.length + 1)) - res.redirect(301, serverurl + urlpath + query) - } else { - next() - } -}) +app.use(require('./lib/web/middleware/redirectwithoutTrailingSlashes')) // routes need sessions // template files diff --git a/lib/web/middleware/checkURiValid.js b/lib/web/middleware/checkURiValid.js new file mode 100644 index 0000000..88065e7 --- /dev/null +++ b/lib/web/middleware/checkURiValid.js @@ -0,0 +1,14 @@ +'use strict' + +const logger = require('../../logger') +const response = require('../../response') + +module.exports = function (req, res, next) { + try { + decodeURIComponent(req.path) + } catch (err) { + logger.error(err) + return response.errorBadRequest(res) + } + next() +} diff --git a/lib/web/middleware/redirectWithoutTrailingSlashes.js b/lib/web/middleware/redirectWithoutTrailingSlashes.js new file mode 100644 index 0000000..fbaba61 --- /dev/null +++ b/lib/web/middleware/redirectWithoutTrailingSlashes.js @@ -0,0 +1,17 @@ +'use strict' + +const config = require('../../config') + +module.exports = function (req, res, next) { + if (req.method === 'GET' && req.path.substr(-1) === '/' && req.path.length > 1) { + const queryString = req.url.slice(req.path.length) + const urlPath = req.path.slice(0, -1) + let serverURL = config.serverurl + if (config.urlpath) { + serverURL = serverURL.slice(0, -(config.urlpath.length + 1)) + } + res.redirect(301, serverURL + urlPath + queryString) + } else { + next() + } +}