Node.js的框架-express

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

  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 進階版

expresscss

  1. 構成
    • 中間件
      • 名詞解釋: 中間件就是一個封裝函數,具備必定的功能
      • express的中間件有哪些呢?
        • 應用級中間件
        • 路由中間件
        • 錯誤處理中間件
      • 中間件如何調用?
        • app對象來調用
          • app.use(中間件)

app.jshtml

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-generatornode

  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
相關文章
相關標籤/搜索