zoukankan      html  css  js  c++  java
  • express 阮一峰的博客

    http://javascript.ruanyifeng.com/nodejs/express.html

    next没怎么用过...

    一个不进行任何操作、只传递request对象的中间件

    function uselessMiddleware(req, res, next) { 
        next();
    }
    

    上面代码的next为中间件的回调函数。如果它带有参数,则代表抛出一个错误,参数为错误文本

    function uselessMiddleware(req, res, next) { 
        next('出错了!');
    }
    

    抛出错误以后,后面的中间件将不再执行,直到发现一个错误处理函数为止。

    response.sendFile方法用于发送文件。

    response.render方法用于渲染网页模板。就像ejs支持html一样

    routes挂载路径

    var router = express.Router();
    
    router.get('/', function(req, res) {
        res.send('首页');    
    });
    
    router.get('/about', function(req, res) {
        res.send('关于');    
    });
    
    app.use('/', router);
    

    如果最后一行改为app.use('/app', router),则相当于/app和/app/about这两个路径,指定了回调函数

     

    use方法为router对象指定中间件,即在数据正式发给用户之前,对数据进行处理。下面就是一个中间件的例子

    router.use(function(req, res, next) {
        console.log(req.method, req.url);
        next();  
    });
    

      

    router对象的param方法用于路径参数的处理

    router.param('name', function(req, res, next, name) {
        // 对name进行验证或其他处理……
        console.log(name);
        req.name = name;
        next();  
    });
    
    router.get('/hello/:name', function(req, res) {
        res.send('hello ' + req.name + '!');
    });
    

    上面代码中,get方法为访问路径指定了name参数,param方法则是对name参数进行处理。注意,param方法必须放在HTTP动词方法之前

    为什么不在get中验证呢?

    路由方式

    在app.js中,路由/admin-->admins.js,在admin.js中,/getAdmin-->function a;

    总的来说:/admin/getAdmin-->function a;

    ejs 传值

    res.render('index', {title: "sfp"});

    locals

      app.locals.moment = require('moment');  // moment这个插件,在页面中也能用了。

  • 相关阅读:
    《构建之法》第五章读后感
    《构建之法》第四章读后感
    《构建之法》第三章读后感
    《构建之法》第二章读后感
    《构建之法》第一章读后感
    web mis系统构建
    异常
    多态
    接口与继承
    个人总结_5.8
  • 原文地址:https://www.cnblogs.com/wang-jing/p/4270968.html
Copyright © 2011-2022 走看看