美文网首页
十、express中间件

十、express中间件

作者: 向上而活 | 来源:发表于2020-04-16 17:52 被阅读0次

    如果 get、post回掉函数中没有next参数,那麽当匹配到第一个路由之后,就不会匹配后一个路由了。

    app.get('/',function(req,res){
        console.log('1');
    })
    app.get('/',function(){
        console.log('2');   
    })
    //只会执行第一个get
    
    app.get('/',function(req,res,next){
        console.log('1');
        next();
    })
    app.get('/',function(){
        console.log('2');   
    })
    //两个get都会执行
    

    下面两个请求看似没有关系,实际上冲突了,因为admin可以充当用户名,login可以充当id。

    app.get("/:username/:id",function(req,res){
        res.send('用户名:'+req.params.username+'。id:'+req.params.id)
    })
     app.get("/admin/login",function(req,res){
        res.send('管理员登陆')
    })
    
    //当在浏览器中运行 127.0.0.1/yangyi/01时,输出 用户名:yangyi。id:01。
    //当在浏览器中运行 127.0.0.1/admin/login时,输出 用户名:admin。id:login。
    
    

    解决方式一:两者交换位置。express中的路由(中间件)的位置很重要,匹配到第一个,就不会往下继续匹配了。所以,具体的往上写,抽象的往下写。

    app.get("/admin/login",function(req,res){
        res.send('管理员登陆')
    })
    app.get("/:username/:id",function(req,res){
        res.send('用户名:'+req.params.username)
    })
     //当在浏览器中运行 127.0.0.1/yangyi/01时,输出 用户名:yangyi。id:01。
    //当在浏览器中运行 127.0.0.1/admin/login时,输出 管理员登陆。
    
    

    解决方式二:

    app.get("/:username/:id",function(req,res,next){
        res.send('用户名:'+req.params.username);
        if(检索数据库){
            console.log(1);
            res.send('用户信息');
        }else{
            next();
        }
    })
    app.get("/admin/login",function(req,res){
        res.send('管理员登陆')
    })
    
    

    app.use()也是中间件,与app.post、app.get的区别是,app.use不仅仅可以匹配精确的地址,还可以有小文件拓展。

    app.use('/admin',function(req,res){
        //访问地址为 http://127.0.0.1:3000/admin/01
    
        res.write(req.originalUrl+"\n");// /admin/01
        res.write(req.baseUrl+"\n");// /admin
        res.write(req.path+"\n");// /01
        res.end("你好");
    })
    

    任何路径都能匹配到

    app.use('/',function(req,res){
        console.log(new Date());
    })
    //等同于
    app.use(function(req,res){
        console.log(new Date());
    })
    

    app.use给特定功能提供了写代码的地方

    app.use(fun);
    function(req,res,next){
        var filePath=req.originalUrl;
        //根据当前的网址,读取public文件夹中的文件
        //如果有这个文件,那麽渲染这个文件
        //如果没有这个文件,那麽next();
        fs.readFile("./public/"+filePath,function(err,data){
            if(err){
                //文件不存在
                next()
                return;
            }
            res.send(data.toString());
        })
    }
    

    静态服务

    var express=require('express');
    var app=express();
    
    //静态服务
    app.use(express.static("./public"))
    
    app.use('/aaa',express.static("./public"))
    

    相关文章

      网友评论

          本文标题:十、express中间件

          本文链接:https://www.haomeiwen.com/subject/aolhectx.html