express-路由(router)

后端:一个路由就是一个小的服务(server/app)
前端:路由就告诉你应该去哪儿

  1. 路由操作(简易)

    1. let routerUser = express.Router();//返回路由对象
    2. server.use(‘/user’,routerUser);//响应的处理过程
    3. 处理过程:
      • router.get(‘/‘,fn);
      • router.get(‘/1’,fn);
      • router.get(‘/2’,fn);
      • router.get(‘/3’,fn);
  2. 路由操作(常用)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    // 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 session
    server.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为session
    maxAge: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;
    }
文章目录
|