Express基於Node.js的Web開發框架 --筆記

從學Node.js語法開始,到Node.js的Web開發相關內容:再到引入Express框架,似乎理解了底層源碼之後,再來看Express框架,似乎就很簡單啦。
Node.js的Web開發相關內容:

  1. Node.js 不需要依賴第三方應用軟件(Apache) 可以基於API自己去實現
  2. 實現靜態資源服務器
  3. 路由處理
  4. 動態路由
  5. 模板引擎
  6. get和post參數的處理

也許就是爲了開發的方便,從而誕生了Express框架,要是基於Node.js去託管一個靜態的網頁的話,也許需要這麼寫

const fs = require('fs');
const path = require('path')
const mime = require('./mime.json')
exports.staticServer = (req,res, root) => {
    fs.readFile(path.join(root,req.url),'utf8', (err, fileContent) => {
        if(err){
            res.writeHead(500,{
                "Content-Type" : "text/plain;charset=utf8"
            })
            res.end("請求的頁面不存在")
        }else{
            let ext = path.extname(req.url);
            let dtype = mime[ext] || 'text/html';
            if(dtype.startsWith('text')){
                dtype += ';charset=utf8';
            }
            res.writeHead(200,{
                "Content-Type" : dtype
            })
            res.end(fileContent);
        }
    })
}
```js

搭建一個動態的服務器還需要模板引擎(art-template):

```js
const http = require('http')
const ss = require('./06.js');
const url = require('url')
const querystring = require("querystring")
const path = require('path')
http.createServer((req, res) => {
    // 啓動靜態資源

    // if(req.url.startsWith('/www')){
    //     ss.staticServer(req,res,__dirname);
    // }
    // 
    ss.staticServer(req,res,path.join(__dirname));  // 託管靜態的網頁
    // 動態資源
    if(req.url.startsWith('/login')){
        if(req.method == 'GET'){
            let param = url.parse(req.url, true).query;
            res.writeHead(200,{
                "Content-Type" : "text/plain;charset=utf8"
            })
            if(param.username == 'admin' && param.password == '123'){
                
                res.end("GET驗證成功!")
            }else{
                res.end("GET驗證失敗")
            }
        }
        if(req.method == "POST"){
            let pdata = '';
            req.on('data',(chunk)=>{
                pdata += chunk;
            })
            req.on('end',()=>{
                let obj = querystring.parse(pdata);
                res.writeHead(200,{
                    "Content-Type" : "text/plain;charset=utf8"
                })
                if(obj.username == 'admin' && obj.password == '123'){
                    res.end("登入成功");
                }else{
                    res.end("POST 驗證失敗")
                }
            })
        }
    }
}).listen(3005,()=>{
    console.log("running");
})

所以Express框架的出現,改善了這個現狀。

const express = require('express')
const app = express()

// 監聽的路徑是‘/‘
app.get('/Home', (req, res) => {
    res.send("OK!");
}).listen(3000, () => {
    console.log("running....");
})
app.use(express.static('public'));
app.use(express.static('myexpress'));

完美的封裝了一個基於Node.js的Web開發框架。

Express基本使用

中間件

Express是一個路由和中間件Web框架,其自身的功能很少:Express應用程序本質上是一系列中間件函數調用。
自己的理解就是 中間件是處理過程中的一個環節(本質上就是一個函數) next() 把下一個請求傳遞給下一個中間件
路由處理程序使您可以爲一個路徑定義多個路由。
通過next() 就實現了 將控制權傳遞給下一個中間件。如果要是當前中間件功能結束請求-響應週期,那麼請求將會掛起。

要從路由器中間件堆棧中跳過其餘中間件功能,請調用next('route')將控制權傳遞給下一條路由。
注意next('route')僅在使用app.METHOD()router.METHOD()函數加載的中間件函數中有效。

使用中間件
接下來要講的參數的處理也需要用到第三方中間件body-parser

參數處理

對於一個路徑的請求,通過路由的分發,請求方式的不同,自然獲取的數據方式也不一樣,對於常見的get post put delete請求的方式,Express是如何解決的呢?讓我們來做個筆記把。

get請求的話,不需要第三方的中間件,通過回調函數中req.query自然可以獲取到Obj對象。
POST請求的方式,需要引入第三方的中間件,body-parser 然後將body-parser實例解析器添加相應的路由中去,也就是需要以下命令 掛載中間件
app.use(bodyParser.urlencoded({ extended: false }))
對於傳入的數據形式是JSON格式的話,我們需要做的內容就是將
app.use(bodyParser.json()) 完成處理Json格式的數據

const express =  require('express');
const app =  express();
let bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
// 掛載參數處理中間件
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
// 處理JSON格式的數據
app.use(bodyParser.json())

// 掛載內置的中間件 就是將靜態的文件託管
app.use(express.static('public'));
// 處理get提交參數
app.get('/login',(req, res) => {
    let pdata = req.query;
    console.log(pdata);
    res.send("接受數據完成!");
})
// 接受參數post請求
app.post('/login',(req, res) => {
    let pdata = req.body;
    console.log(pdata);
    res.send("數據完成post請求!");
})
app.listen(3000, () =>{
    console.log("Express---running....")
})


模板引擎

Express中使用art-template模板引擎的話 需要兼容它
具體做法如下:

npm install --save art-template
npm install --save express-art-template

然後設置模板引擎的文件位置

app.set('views', path.join(__dirname, 'views'));//設置模板引擎的路徑

Express一起使用的一些流行模板引擎是Pug, Mustache和EJS。
當然我這裏使用的是art-template

app.set('view engine','art')     // 設置模板引擎  'art' 就是模板引擎的後綴

最後通過res.render(“op1”,‘op2’);
op1 表示的是模板對應的文件名稱
op2 對應的就是渲染的數據

const express = require('express');
const path = require('path')
const app = express();
const template = require('art-template')
app.set('views', path.join(__dirname, 'views'));   // 設置模板引擎的路徑
app.set('view engine','art')     // 設置模板引擎  'art' 就是模板引擎的後綴
app.engine('art', require('express-art-template'));  // 使express兼容art-templatte模板引擎
app.get('/list', (req, res) =>{
    let data = {
        title : '這個是使用到了art-tmplate模板引擎',
        name : '數據的渲染是需要一個過程的'
    }
    // render是art-template中的方法 
    // 參數一: 是一開始設置模板引擎文件也就是views文件中 指定文件的名稱
    // 參數二:渲染模板的數據
    res.render("test",data);
})
app.listen(3000, () => {
    console.log("running....");
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章