• node(三)express框架


    1.express介绍

    是一个基于Node平台的极简、灵活的WEB应用开发框架,官网地址:https://www.expressjs.com.cn/
    简单来说,express是一个封装好的工具包,封装了很多功能,便于开发Web应用(HTTP服务)。

    2.express初体验

    const express = require('express');
    
    const app = express();
    
    app.get('/home',(req,res) => {
        res.send('hello express');
    });
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.express路由

    3.1什么是路由?

    路由确定了应用程序如何响应客户端对特定端点的请求。

    3.2路由的使用

    一个路由的组成有请求方法,路由和回调函数组成。
    express中提供了一系列方法,可以很方便的使用路由,使用格式如下:

    app.<method>(path,callback)
    
    • 1
    const express = require('express');
    
    const app = express();
    
    app.get('/home',(req,res) => {
        res.send('hello express');
    });
    
    app.get('/',(req,res) => {
        res.end('home');
    });
    
    app.get('/login',(req,res) => {
        res.end('login login');
    });
    
    app.post('/login',(req,res) => {
        res.end('login');
    });
    // 无论什么方法都可以
    app.all('/test',(req,res) => {
        res.end('test test');
    });
    app.all('*',(req,res) => {
        res.end('404 not Found');
    });
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    })
    
    • 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

    3.3获取请求参数

    express框架封装了一些API来方便获取请求报文中的数据,并且兼容HTTP模块的获取方式。

    const express = require('express');
    
    const app = express();
    
    app.get('/request',(req,res) => {
        // 原生操作
        console.log(req.method);
        console.log(req.url);
        console.log(req.headers);
        console.log(req.httpVersion);
        res.end('hello express');
        // express操作
        console.log(req.method);
        console.log(req.query);
        // 获取操作
        console.log(req.ip);
        // 获取请求头
        console.log(req.get('host'));
    });
    
    app.listen(3000,() => {
        console.log('111');
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.4获取路由参数

    路由参数指的是URL路径中的参数

    const express = require('express');
    
    const app = express();
    
    app.get('/:id.html',(req,res) => {
        console.log(req.params.id);
        res.setHeader('content-type','text/html;charset=utf-8');
        res.end('商品详情');
    });
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4.express响应设置

    给客户端响应数据

    const express = require('express');
    
    const app = express();
    
    // app.get('/response',(req,res) => {
    //     // 原生响应
    //     // res.statusCode = 404;
    //     // res.statusMessage = 'love';
    //     // res.setHeader('xxx','yyy');
    //     // res.write('hello express');
    //     // res.end('responese');
    
    //     // express响应
    //     // res.status(500);
    //     // res.set('aaa','bbb');
    //     // res.send('你好 express');
    //     // 连贯操作
    //     // res.status(500).set('abc','def').send('ok');
    
    
    // });
    
    // 其他响应
    app.get('/other',(req,res) => {
        // 跳转响应
        // res.redirect('https://www.baidu.com');
        // 下载响应
        // res.download(__dirname + '/package.json');
        // JSON响应
        // res.json({
        //     name:'learn',
        //     slogon:'express'
        // })
        // 响应文件内容
        res.sendFile(__dirname + '/test.html');
    });
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    })
    
    • 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

    5.express中间件

    5.1什么是中间件?

    中间件本质是一个回调函数
    中间件函数可以像路由回调一样访问请求对象,响应对象

    5.2中间件的作用

    中间件的作用就是使用函数封装公共操作,简化代码

    5.3中间件类型

    全局中间件

    const express = require('express');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    
    // 声明中间件函数
    function recordMiddleware(req,res,next){
        // 获取url和ip
        let{url,ip} = req;
        console.log(url,ip);
        // 将信息保存在文件中access.log
        fs.appendFileSync(path.resolve(__dirname,'./access.log'), `${url} ${ip}\r\n`);
        // 调用next
        next();
    }
    
    // 使用中间件函数
    app.use(recordMiddleware);
    app.get('/home',(req,res) => {
        res.send('前台首页');
    });
    
    app.get('/admin',(req,res) => {
        res.send('后台首页');
    });
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    });
    
    app.all('*',(req,res) => {
        res.send('

    404 Not Found

    '
    ); })
    • 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

    路由中间件

    const express = require('express');
    const fs = require('fs');
    const path = require('path');
    
    const app = express();
    // 声明中间件
    let checkCodeMiddleware = (req,res,next) => {
        // 判断URL中是否code参数等于521
         // 判断URL中是否code参数等于521
        if(req.query.code === '521'){
            res.send('后台首页');
        }else{
            res.send('暗号错误');
        }
    }
    
    app.get('/home',(req,res) => {
        res.send('前台首页');
    });
    
    
    app.get('/admin', checkCodeMiddleware,(req,res) => {
       res.send('后台首页');
    });
    
    app.get('/setting',checkCodeMiddleware,(req,res) => {
        res.send('设置页面');
    });
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    });
    
    app.all('*',(req,res) => {
        res.send('

    404 Not Found

    '
    ); })
    • 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

    5.4静态资源中间件

    const express = require('express');
    
    const app = express();
    
    // 静态资源中间件设置,将当前文件夹下的public目录作为网站的根目录
    app.use(express.static(__dirname + '/public'));
    
    app.get('/home',(req,res) => {
        res.send('hello express');
    });
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    注意事项:
    1.index.html文件为默认打开的资源
    2.如果静态资源与路由规则同时匹配,谁先匹配谁先响应。
    3.路由响应动态资源,静态资源中间件响应静态资源。

    5.5获取请求体数据body-parser

    express可以使用body-parser处理请求体
    第一步:安装
    npm i body-parser
    第二步:导入body-parser包
    const bodyParser = require(‘body-parser’);
    第三步:获取中间件函数

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>登录页面title>
    head>
    <body>
        <form action="http://127.0.0.1:3000/login" method="post">
            用户名:<input type="text" name="username"><br />
            密码:<input type="password" name="password"> <br />
            <button>登录button>
        form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    // 解析JSON格式的请求体的中间件
    const jsonParser = bodyParser.json();
    
    // 解析queryString格式请求体的中间件
    const urlencodedParser = bodyParser.urlencoded({extended:false});
    
    app.get('/login',(req,res) => {
        res.send('表单页面');
        // 响应HTML文件内容
        res.sendFile(__dirname + '/11form.html');
    });
    
    app.post('/login',urlencodedParser,(req,res) => {
        console.log(req.body);
        res.send('获取用户数据');
    });
    
    app.listen(3000,() => {
        console.log('正在运行...');
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    6.防盗链

    const express = require('express');
    
    const app = express();
    
    // 声明中间件
    app.use((req,res,next) => {
        // 检测请求头中的referer
        // 获取referer
        let referer = req.get('referer');
        // console.log(referer);
        if(referer){
            let url = new URL(referer);
            let hostname = url.hostname;
            // console.log(hostname);
            if(hostname !== '127.0.0.1'){
                res.status(404).send('

    404 Not Found

    '
    ); return; } } next(); }); // 静态资源中间件设置,将当前文件夹下的public目录作为网站的根目录 app.use(express.static(__dirname + '/public')); app.listen(3000,() => { console.log('服务已经启动,端口3000正在监听中....') })
    • 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

    7.路由模块化

    homeRouter.js

    const express = require('express');
    
    const router = express.Router();
    
    // 创建路由规则
    router.get('/home',(req,res) => {
        res.send('前台首页');
    });
    
    // 创建路由
    router.get('/search', (req,res) => {
       res.send('内容搜索');
    });
    
    // 暴露router
    module.exports = router;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    addminRouter.js

    const express = require('express');
    
    const router = express.Router();
    
    // 后台
    router.get('/admin',(req,res) => {
        res.send('后台首页');
    });
    
    router.get('/setting',(req,res) => {
        res.send('设置页面');
    });
    
    module.exports = router;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    const express = require('express');
    const fs = require('fs');
    const path = require('path');
    const homeRouter = require('./routes/homeRouter');
    const adminRouter = require('./routes/addminRouter');
    
    const app = express();
    
    // 设置
    app.use(homeRouter);
    app.use(adminRouter);
    
    
    app.listen(3000,() => {
        console.log('服务已经启动,端口3000正在监听中....')
    });
    
    app.all('*',(req,res) => {
        res.send('

    404 Not Found

    '
    ); })
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    8.EJS模板引擎

    8.1什么是模板引擎

    模板引擎是分离用户界面和业务数据的一种技术

    8.2什么是EJS

    EJS是一个高效的JS模板引擎。
    官网:https://ejs.co/
    中文站:https://ejs.bootcss.com/

    8.3EJS初体验

    下载安装EJS
    01html.html

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <h2>我爱你 <%= china %>h2>
        <p><%= weather %>p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    // 安装ejs
    const ejs = require('ejs');
    const fs = require('fs');
    
    // 字符串
    let china = '中国';
    let weather = '今天天气不错...';
    // let str = `我爱你 ${中国}`;
    
    // let str = '我爱你 <%= china %>';
    let str = fs.readFileSync('./01html.html').toString();
    
    // 使用ejs渲染
    let result = ejs.render(str,{china:china,weather});
    console.log(result);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    8.4EJS列表渲染

    02西游.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <ul>
            <% xiyou.forEach(item=> { %>
                <li><%= item %></li>
            <% }) %>
        </ul>
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    列表渲染.js

    const ejs = require('ejs');
    
    const xiyou = ['1','2','3','4'];
    
    // 原生JS
    // let str = '
      '; // xiyou.forEach(item => { // str += `
    • ${item}
    • `;
      // }) // str += '
    ';
    // console.log(str); // EJS实现 const fs = require('fs'); let html = fs.readFileSync('./02西游.html').toString(); let result = ejs.render(html,{xiyou:xiyou}); console.log(result);
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    8.5EJS条件渲染

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <% if(isLogin){ %>
        <span>欢迎回来</span>
        <% }else { %>
            <button>登录</button> <button>注册</button>
        <% } %>
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    // 
    const ejs = require('ejs');
    let isLogin = true;
    
    // if(isLogin){
    //     console.log('欢迎回来');
    // }else{
    //     console.log('  ');
    // }
    
    // EJS实现
    const fs = require('fs');
    let html = fs.readFileSync('./03条件渲染.html').toString();
    let result = ejs.render(html,{isLogin:isLogin});
    
    console.log(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    8.6express使用EJS

    8.7express-generator工具

    express应用程序生成器可以快速创建一个应用的骨架。
    全局安装:

    >npm install -g express-generator
    
    • 1

    快速构建express -e 要文件夹名称

  • 相关阅读:
    c++复习——名字粉碎
    vue+element纯手工完美模拟实现小米有品网站
    Scrapy设置代理IP方法(超详细)
    K8S笔记 - 查看微服务日志
    java图书管理系统
    因势而变,因时而动,Go lang1.18入门精炼教程,由白丁入鸿儒,Go lang泛型(generic)的使用EP15
    板凳---------unix网络编程卷1:第二章传输层:TCP、UDP 和 SCTP
    adas自动驾驶叉车CAN通讯隔离EMC解决方案
    SpringCloud原生组件之OpenFeign远程调用
    SPI:Java的高可扩展利器
  • 原文地址:https://blog.csdn.net/qq_52986400/article/details/134083898