zoukankan      html  css  js  c++  java
  • Node.js的框架-express

    Node.js的框架
    express 是第三方的

    1. express
    const express=require('express');
    const app=express();
    const PORT=3000
    const HOST='localhost'
    
    //创建路由/路由中间件
    //目标http://localhost:8000/home
    app.get('/home',(req,res,next)=>{
        // req:请求
        // res:响应
        // next:请求与响应之间的连接
        res.send('平安夜')
        // res.json({
        //     name:'李兰生',
        //     day:'平安夜'
        // })
    })
    //监听服务器
    app.listen(PORT,HOST,()=>{console.log( `xpress创建的服务器在:http://${ HOST }:${PORT}`);
    })
    
    1. koa express 进阶版

    express

    1. 构成
      • 中间件
        • 名词解释: 中间件就是一个封装函数,具有一定的功能
        • express的中间件有哪些呢?
          • 应用级中间件
          • 路由中间件
          • 错误处理中间件
        • 中间件如何调用?
          • app对象来调用
            • app.use(中间件)

    app.js

    const express=require('express');
    const app=express();
    const cors= require('cors');
    const PORT=3000
    const HOST='localhost'
    
    
    app.use(cors())
    //创建路由/路由中间件
    //目标http://localhost:8000/home
    app.get('/home',(request,response,next)=>{
    //跨域请求头
    // response.setHeader('Access-Control-Allow-Origin','*');
    
    
    const http = require('http')
    const cheerio = require('cheerio')
    
    const options = {
      hostname: 'jx.1000phone.net',
      port: 80,
      path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiZ2Zn',
      method: 'GET',
      headers: {
        Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        Cookie: 'PHPSESSID=ST-117984-IVZSfYMlr9YXvRfFRm-A1TimOeA-izm5ejd5j1npj2pjc7i3v4z',
        Host: 'jx.1000phone.net',
        Pragma: 'no-cache',
        Referer: 'http://jx.1000phone.net/teacher.php/Class/index',
        'Upgrade-Insecure-Requests': 1,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': 0
      }
    }
    
    http.get(options, (res) => {
      /* res就是我得到的返回值 */
      const { statusCode } = res; // 状态码
      const contentType = res.headers['content-type']; // 得到的文件类型
    
      res.setEncoding('utf8'); // 中文编码
      let rawData = ''; // 真实数据
      res.on('data', (chunk) => { rawData += chunk; });// 通过data事件将数据分片,然后逐片添加到rawData身上,好处就是当我们执行每一个分片的小任务时,至少给其他任务提供了可执行的机会
      res.on('end', () => { // 表示结束
        try { // 高级编程 错误捕获
          const $ = cheerio.load( rawData )
          let arr=[];
          $('.student a').each(function ( index,itm ) {
            // console.log( $( this ).text() ) // 每一个的内容
            arr.push( {
                id:index+1,
                name:$( this ).text()
            });
           
          })
          response.json( arr);
        } catch (e) {
          console.error(e.message);
        }
      });
    
    
    }).on('error', (e) => {
      console.error(`Got error: ${e.message}`);
    });
    })
    //监听服务器
    app.listen(PORT,HOST,()=>{console.log( `xpress创建的服务器在:http://${ HOST }:${PORT}`);
    })
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
      <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    
    </head>
    <body>
        <button> 获取数据 </button>
        <br>
        <table>
          <thead>
            <tr> <td>编号</td> <td> 姓名 </td> </tr>
          </thead>
          <tbody>
      
          </tbody>
        </table>
    </body>
    <script>
    const baseURL='http://localhost:3000'
    
    $('button').on('click',function(){
    //     $.ajax({
    //     url:`${baseURL}/home`,
    //     success(res){
    //         console.log(res);
    //     }
    // })
        $.ajax({
            url:`${baseURL}/home`,
            success(res){
                let str=``;
                for(var item of res){
                    str+=`<tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        </tr>`
                }
                $('tbody').html(str)
            }
        })
    })
    </script>
    </html>
    
    • 路由
      • 前端: 接口
      • 后端: 路由
    1. 跨域【 后端跨域 】

      • 设置请求头
      • response.setHeader('Access-Control-Allow-Origin','*')
      • 利用第三方模块来跨域 cors
    2. 使用工程化工具来构建一个完整的 express 项目

      • 工程化工具/自动化工具/脚手架
        • express-generator
          • express-generator 使用
              1. 安装
              • $ cnpm i express-generator -g
              • $ express -e 项目名称
            • OR
              1. 不安装使用
              • 保证你的电脑中npm版本 > 5.2
              • $ npx express -e 项目名称
            • 名词解释: -e 表示ejs文件,它是一个html模板

    express-generator

    1. 目录
      • bin/www 为项目创建了一个服务器
      • public 静态资源文件夹
        • img
        • style
        • js
      • routes 路由
      • views
        • 路由对应的模板,这个模板将来会发送给前端,发给前端前会被解析为html文件
      • app.js 项目入口文件
    // 项目需要的第三方模块
    var createError = require('http-errors');//记录错误信息
    var express = require('express');//express的顶级库,提供espres api
    var path = require('path');//处理磁盘路径
    var cookieParser = require('cookie-parser');//cookie
    var logger = require('morgan');//记录日志信息
    
    //引入自定义的路由中间件
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    
    //创建app对象
    var app = express();
    
    // 视图引擎设置
    app.set('views', path.join(__dirname, 'views'));//处理view的绝对路径
    app.set('view engine', 'ejs');//设置项目模板渲染引擎为ejs
    
    //通过app对象来使用中间件
    app.use(logger('dev'));
    app.use(express.json());//为post请求做格式化
    app.use(express.urlencoded({ extended: false }));//项目文件可以省略项目后缀
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));//确定项目资源静态目录指定为pubic
    
    //调用路由中间件  创建接口
    app.use('/api', indexRouter);
    app.use('/api', usersRouter);
    
    
    // 捕获404并转发给错误处理程序(错误中间件)
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    //错误处理程序
    app.use(function(err, req, res, next) {
      // 设置局部变量,只提供开发中的错误
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // 渲染错误页面
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;
    
    • packge.json
      • 表示项目启动脚本记录 、 项目所需要的依赖包【 插件 】
      • npm install
      • npm run start
    1. Node.js可以当做一个后端的角色

      • 能不能给前端做接口
      • 去熟悉项目运行思维
        • package.json -> node ./bin/www -> app.js -> routes/index.js & users.js
    2. 后端测试接口

      • postman
      • insomnia
  • 相关阅读:
    Android Studio 开发
    Jsp编写的页面如何适应手机浏览器页面
    电影
    Oracle 拆分列为多行 Splitting string into multiple rows in Oracle
    sql server 2008 自动备份
    WINGIDE 激活失败
    python安装 错误 “User installations are disabled via policy on the machine”
    ble编程-外设发送数据到中心
    iOS开发-NSString去掉所有换行及空格
    ios9 字符串与UTF-8 互相转换
  • 原文地址:https://www.cnblogs.com/lilansheng/p/12093926.html
Copyright © 2011-2022 走看看