zoukankan      html  css  js  c++  java
  • 从零开始学习Node.js例子四 多页面实现数学运算 续一(使用connect和express框架)

    1、使用connect框架
    .use方法用于绑定中间件到connect服务器,它会配置一系列在接到请求时调用的中间件模块,此例中我们要配置的中间件有favicon logger static router
    app.get/post/put        写法:app.requestName('path', function(req, res, next){});

    app-connect.js

     var connect = require('connect');   //npm install connect
     connect.createServer()
         .use(connect.favicon())
         .use(conect.logger())
         .use('/filez', connect.static(__dirname + '/filez'))
         .use(connect.router(function(app){
             app.get('/', require('./home-node').get);
             //一个URL字符串和两个函数类型的参数
             //路由器配置函数可以包含不限数量的函数,你可以为自己的应用构造一个处理函数的队列
             app.get('/square', htutil.loadParams, require('./square-node').get);
             app.get('/factorial', htutil.loadParams, require('./factorial-node').get);
             app.get('/fibonacci', htutil.loadParams, require('./fibo2-node').get);
             app.get('/mult', htutil.loadParams, require('./mult-node').get);
         })).listen(3000);
    
    console.log('listening to http://localhost:3000');

    2、使用express框架

    Express框架是一个基于connect(一个中间件框架)的web应用框架
    Express专注于构建一个应用,包括提供一个模板系统;connect专注于做web服务的基础设施

    安装Express和EJS(模块处理系统) npm install express ejs

    app-express.js

    var htutil = require('./htutil');
    var math = require('./math');
    var express = require('express');
    
    //var app = express.createServer(express.logger());  //express 2.X
    var app = express();    //express 3.X
    
    //可选,因为Express下默认为CWD/views
    app.set('views', __dirname + '/views');
    app.engine('.html', require('ejs').__express);
    app.set('view engine', 'ejs');
    app.configure(function(){
        app.use(app.router);
        app.use(express.static(__dirname + '/filez'));
        //默认的错误处理函数,显示栈轨迹
        //如果要显示用户友好的错误,app.err(function(err, req, res, next){
        // res.send(error page);  //or res.render('template');
        // });
        app.use(express.errorHandler({
            dumpExceptions: true, showStack: true
        }));
    /*
    改成下面的话,浏览器会显示一个简单的消息-Internal Server Error内部服务器错误
    app.use(express.errorHandler({
            dumpExceptions: true
        }));
    */
    });
    //以上配置了必需的中间件,因为这里展示的配置项对应的是模板系统的配置,所有.html文件会由EJS引擎处理
    
    //以下是路由器配置
    app.get('/', function(req, res){
        res.render('home.html', {title: "Math Wizard"});
    });
    app.get('/mult', htutil.loadParams, function(req, res){
        if (req.a && req.b) req.result = req.a * req.b;
        res.render('mult.html', {title: "Math Wizard", req: req});
    });
    app.get('/square', htutil.loadParams, function(req, res){
        if (req.a) req.result = req.a * req.a;
        res.render('square.html', {title: "Math Wizard", req: req});
    });
    app.get('/fibonacci', htutil.loadParams, function(req, res){
        if (req.a){
            math.fibonacciAsync(Math.floor(req.a), function(val){
                req.result = val;
                res.render('fibo.html', {title: "Math Wizard", req: req});
            });
        }else {
            res.render('fibo.html', {title: "Math Wizard", req: req});
        }
    });
    app.get('/factorial', htutil.loadParams, function(req, res){
        if (req.a) req.result = math.factorial(req.a);
        res.render('factorial.html', {title: "Math Wizard", req: req});
    });
    app.get('/404', function(req, res){
        res.send('NOT FOUND' + req.url);
    });
    
    //res.render函数通过一个模板文件渲染数据,EJS只是Express里众多模板引擎中的一个
    //配置目的是让EJS能够为views目录下的所有.html文件服务
    /*Express里还有其他一些模板引擎
        res.render('index.haml', {..data..}); 使用Haml
        res.render('index.jade', {..data..}); 使用Jade
        res.render('index.ejs', {..data..}); 使用EJS
        res.render('index.coffee', {..data..}); 使用CoffeeKup
        res.render('index.jqtpl', {..data..}); 使用jQueryTemplates
    
    也可以通过 app.set('view engine', 'haml');
              app.set('view engine', 'jade'); 方法来改变默认的渲染引擎
    
    layout.html
    默认情况下,模板中用于渲染的内容会被命名为body,然后传递到layout模板中,当app-express.js调用
    res.render('fibo.html'...)时,它会先用fibo.html渲染对应的页面片段,然后再使用layout模板渲染整个页面
    有两种方法覆盖这一默认的行为
    1、在Express里创建一个全局的配置,通过这个全局配置来控制layout模板的启用与禁用
    app.set('view options', {layout: false(or true)});
    2、覆盖layout模板对应的渲染方式或者使用不同的layout模板
    res.render('myview.ejs', {layout: false(or true)});
    或者res.render('page', {layout: 'mylayout.jade'});
    
    <% code %> Javascript代码
    <%= code %> 显示替换过HTML特殊字符的内容
    <%- code %> 显示原始HTML内容
    */
    
    app.listen(3000);
    console.log('listening to http://localhost:3000');

    html页面放在views目录下

    layout.html

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <h1><%=title%></h1>
        <table>
            <tr>
                <td>
                    <div class="navbar">
                        <p><a href="/">home</a></p>
                        <p><a href="/mult">Multiplication</a></p>
                        <p><a href="/square">Square</a></p>
                        <p><a href="/factorial">Factorial</a></p>
                        <p><a href="/fibonacci">Fibonacci</a></p>
                    </div>
                </td>
                <td></td>
            </tr>
        </table>
    </body>
    </html>

    home.html

    <% include layout.html %>
    <p>Math Wizard</p>

    mult.html

    <% include layout.html %>
    <% if (req.a && req.b){ %>
        <p class="result">
            <%=req.a%> * <%=req.b%> = <%=req.result%>
        </p>
    <% } %>
    <p>Enter numbers to multiply</p>
    <form name="mult" action="/mult" method="get">
        A: <input type="text" name="a" /><br/>
        B: <input type="text" name="b" />
        <input type="submit" name="Submit" />
    </form>

    还有其他一些页面就不一一列出来了,都大同小异

  • 相关阅读:
    Java操作excel,读取及导出
    vue 在package.json配置对外暴露访问地址(手机端访问本地项目地址)
    element UI upload组件上传附件格式限制
    linux之vim/vi快速复制多行内容的快捷键
    使用vant的Toast组件时提示not defined
    如何使用js判断当前页面是pc还是移动端打开的
    JavaScript 保留两位小数函数
    Linux其他命令
    linux学习ls的三个选项 lha的作用和隐藏文件的知识
    vue+ element-ui el-table组件自定义合计(summary-method)坑
  • 原文地址:https://www.cnblogs.com/EricaMIN1987_IT/p/3642709.html
Copyright © 2011-2022 走看看