Node.js_express_route 路由

route 路由   (kiss my ass ヾ(゚∀゚ゞ)
html

  • 請求方式        get / post /  put / delete____查 / 增 / 改 / 刪
  • 路由路徑        必須 '/' 開頭       

// hotel.meituan.com/40302829/?ci=2018-12-21&2018-12-22
// 查詢字符串 ?ci=2018-12-21&2018-12-22
// params 4032829express

  • 回調函數句柄函數)        (req 請求信息, res 響應信息)=>{}

req.query        獲取 查詢字符串 參數    GET 請求json

req.params        獲取 params 參數api

req.headers        獲取請求頭的全部信息數組

req.body        獲取請求體參數    POST 請求        瀏覽器

(默認 express 框架是解析不了請求體數據的,須要引入其餘中間件實現)服務器

返回響應(有且只能設置一個方法,不然報錯)app

res.download('./haha.mp4'       返回響應,讓 瀏覽器 自動下載指定文件框架

res.sendFile(__dirname + '/haha.js'       返回響應,讓 瀏覽器 自動打開指定文件函數

res.end()        返回一個快速響應

res.json()        返回響應,將傳入的 數據 轉化爲 JSON 字符串 返回

res.send()        根據傳入數據的類型 來自動判斷,添加響應的響應頭處理,相對較慢

如: <h1></h1>    會自動加上    content-type text/html; charset=utf-8

{xxx: xxx}    自動轉化爲 JSON,並返回

res.redirect('https://www.baidu.com')        返回響應,將 請求資源 重定向到新的地址,默認響應狀態碼 302

res.get()        獲取 響應頭 的內容

res.set('content-type', 'text/html; charset=utf-8')        設置 響應頭 的內容

res.status(500)        設置 響應狀態碼 的內容    res.status(500).end('test');

解析規則:

全部路由和中間件都在一個數組中,js 引擎會按照代碼前後順序添加路由和中間件
當請求發送到服務器時,服務器獲取當前的請求信息(請求方式、請求路由路徑)
遍歷數組,找到第一個匹配(請求路由路徑和請求方式必須徹底一致)到的路由或者中間件,執行其回調函數

意味着: 聲明多個同名路由時,始終解析第一個成功解析的路由

若是沒找到,返回一個狀態碼爲 404 的響應, Cannot GET / xxx 或者 Cannot POST / xxx

  • // 1. 導入 express 模塊
    const express =  require('express');
    
    // 2. 建立 app 應用對象
    const app = express();
    
    // 3. 寫業務邏輯:處理請求,返回響應
    
        // route 路由的組成: app.請求方式('/路由路徑', 句柄函數);
        app.get('/login', (request, response)=>{
            console.log(request.query);
            response.send('Login Page Response!');
        });
    
        app.post('/register', (request, response)=>{
            console.log(request.query);
            response.send('Register Page Response!');
        });
        
        app.post('/shop/a', (request, response)=>{
            console.log(request.query);
            response.send('Shop/a Page Response!');
        });
        
        app.post('/shop/b', (request, response)=>{
            console.log(request.query);
            response.send('Shop/b Page Response!');
        });
        
        //hotel.meituan.com/40302829/?ci=2018-12-21&2018-12-22
        // 查詢字符串        ?ci=2018-12-21&2018-12-22
        // params        4032829
    
        // /:id 路由, 一類路由的集合處理
        app.post('/hotel/:id', (request, response)=>{
            console.log(request.params);    // {id: '123456'}
            response.send('Shop/b Page Response!');
        });
    
    // 4. 監聽端口號:一個端口號 有且只能運行 一個程序
    app.listen(3000, err=>console.log(err?err:'服務器啓動成功 :  http://127.0.0.1:3000'));
相關文章
相關標籤/搜索