后端:一个路由就是一个小的服务(server/app)
前端:路由就告诉你应该去哪儿
路由操作(简易)
- let routerUser = express.Router();//返回路由对象
- server.use(‘/user’,routerUser);//响应的处理过程
- 处理过程:
- router.get(‘/‘,fn);
- router.get(‘/1’,fn);
- router.get(‘/2’,fn);
- router.get(‘/3’,fn);
路由操作(常用)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// 1. 主服务(server.js/index.js)let express = require('express');let multer = require('multer');let cookieParser = require('cookie-parser');let cookieSession = require('cookie-session');let bodyParser = require('body-parser');let consolidate = require('consolidate'); //中间件,管理多个模板引擎let mysql = require('mysql');let server = express();server.listen(8001,function(){trueconsole.log('server is running');});server.use(express.static('./www'));server.use(bodyParser.urlencoded({limit:5*1024}));let objMulter = multer({dest:'upload'});server.use(objMulter.any());server.set('views','./views');//设置模板引擎目录server.set('view.engine','html');//设置输出类型server.engine('html',consolidate.ejs);//输出与模板匹配//cookie sessionserver.use(cookieParser());// let arr=[];// for(let i=0;i<10000;i++){// arr.push('myse'+Math.random());// }server.use(cookieSession({keys:['aa','bb'],//加密name:'session',//sessionkey为sessionmaxAge:1000*10//10秒后过期}));//创建数据库连接池let db = mysql.createPool({truehost:'localhost',trueuser:'root',truepassword:'123456',truedatabase:'test'});server.use('/',require('./router/home')(db))server.use('/article',require('./router/article')(db));server.use('/column',require('./router/column')(db));server.use('/fllow',require('./router/fllow')(db));server.use('/user',require('./router/user')(db));server.use('/login',require('./router/login')(db));server.use('/reg',require('./router/reg')(db));//2.新建router文件//在router文件中写各个服务模块//`column模块`示例:let express = require('express');module.exports=function(db){truelet router =express.Router();truerouter.get('/',(req,res)=>{truetruelet sql = `select * from news`;truetruedb.query(sql,(err,data)=>{truetruetrueres.render('column_m.ejs',{news:data});truetrue})true})truereturn router;}