# 修改app.js增加访问控制部分的代码 ``` var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); //引入下面的文件 var fs = require('fs'); var tools = require('./libs/tools'); var config = require(tools.rootPath + 'config'); var app = express(); // view engine setup app.set('views', path.join(tools.viewPath)); //修改模板后缀为html app.engine('.html', require('ejs').__express); app.set('view engine', 'html'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); //diy中间件 app.use(function (req, res, next) { //缓存头,内容头,跨域请求头 res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Content-type', 'text/html;charset=utf-8'); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); //解析模块MM、控制器CC、操作AA let p = (req.baseUrl + req.path).split('/').splice(1); [req.CC, req.AA] = p; if (typeof (req.CC) == 'undefined' || req.CC == '') req.CC = 'index'; if (typeof (req.AA) == 'undefined' || req.AA == '') req.AA = 'index'; req.MM = req.CC = req.CC.toLowerCase(); req.AA = req.AA.toLowerCase(); console.log('visit:', req.MM, req.CC, req.AA); //模板 req.TPL = req.CC + '/' + req.AA; req.REQUEST_URI = (typeof (req.headers['referer']) != 'undefined' && req.headers['referer']) ? req.headers['referer'] : ''; req.isPost = false; req.isGet = false; if (req.method == 'POST') req.isPost = true; if (req.method == 'GET') req.isGet = true; next(); }); app.route('*').all(async function (req, res, next) { //控制器文件 let controllerFile = tools.controllerPath + req.CC + '.js'; if (!fs.existsSync(controllerFile)) { res.status(404); res.render('404', { msg: `controller file not exists!` + req.CC + '.js' }); next(); return; } //包含控制器文件并实例化 var CC = require(controllerFile); let object = new CC(); //初始化变量 object.req = req; object.res = res; //调用初始化方法 await object.init(); //判断方法是否存在 var methods = Object.getOwnPropertyNames(Object.getPrototypeOf(object)); //_开头的是私有方法 if (req.AA.indexOf('_') == 0) { res.status(404); res.render('404', { msg: `action not exists![a]` + req.AA }); next(); return; } //不允许访问的方法 var deny_list = ['constructor', 'init', 'msg', 'tpl', 'json', '__call', '__before', 'assign', 'session', 'redirect', 'post', 'get', 'isAjax', 'referer', 'model', 'action']; if (deny_list.indexOf(req.AA) > -1) { res.status(404); res.render('404', { msg: `action not exists![b]` + req.AA }); next(); return; } if (methods.indexOf(req.AA) == -1) { if (methods.indexOf('__call') > -1) { console.log('__call called!'); //调用__before if (methods.indexOf('__before') > -1) { let result = await object['__before'](req, res); if (!result) { console.log('__before execute fail!'); next(); return; } } //访问不存在的方法时 let result = await object['__call'](req, res); if (typeof (result) != 'undefined') { res.end(result.toString()); } next(); return; } res.status(404); res.render('404', { msg: `action not exists![c]` + req.AA }); next(); return; } //调用__before if (methods.indexOf('__before') > -1) { let result = await object['__before'](req, res); if (!result) { console.log('__before execute fail!'); next(); return; } } //调用方法并发送到浏览器 let result = await object[req.AA](req, res); if (typeof (result) != 'undefined') { res.end(result.toString()); } next(); }); module.exports = app; ``` # 新建/libs/controller.js ``` class controller { constructor() { } init() { } __before() { return true; } } module.exports = controller; ``` # 新建/application/functions.js备用 ``` const fs = require('fs'); var tools = require('../libs/tools'); module.exports = { }; ``` # 新建/application/controllers/index.js ``` const fs = require('fs'); const path = require('path'); var tools = require('../../libs/tools'); var config = require(tools.rootPath + 'config'); var controller = require(tools.rootPath + 'libs/controller.js'); const functions = require(tools.appPath + 'functions'); module.exports = class extends controller { constructor() { super(); } index(req, res) { res.send('hi: ' + Math.random()); } } ``` # 浏览器访问http://192.168.56.103:3000/index/index ![](https://img.kancloud.cn/80/d0/80d0bcd29a70237df02ff4bde13a83d7_458x122.png)