1. 程式人生 > 其它 >二十三.瀏覽器的強制快取與伺服器的自動啟動

二十三.瀏覽器的強制快取與伺服器的自動啟動

  • web頁面程式碼如下
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    </head>
    
    <body>
        <button id="btn">強制快取</button>
        <script>
            $("#btn").click(function () {
                //ajax請求
                $.ajax({
                    url: "/img",
                    type: "get",
                    headers: {
                        "Cache-Control": "max-age=100000"
                    },
                    success(data) {
                        console.log(data);
                    }
                })
            })
        </script>
    </body>
    
    </html>
    
  • 伺服器的自動啟動與強制快取
    const express = require("express");
    const {
        exec
    } = require("child_process")
    const path = require("path");
    const fs = require("fs");
    const app = express();
    app.get("/", (req, res) => {
        const filePath = path.resolve(__dirname, "./index.html");
        /* const rs = fs.createReadStream(filePath);
        rs.pipe(res); */
        res.sendFile(filePath)
    })
    /* 
        強制快取:
        - 強制快取就是向瀏覽器快取查詢該請求結果,並根據該結果的快取規則來決定是否使用該快取結果的過程。
        - 簡單來講就是強制瀏覽器使用當前快取
        - 首先請求頭需要攜帶"Cache-Control"的資訊為"max-age = 時間":客戶端允許開啟強制快取
        - 響應頭需要攜帶"Cache-Control"的資訊為"max-age = 時間":服務端也允許開啟強制快取
    */
    app.get("/img", (req, res) => {
        const filePath = path.resolve(__dirname, "./lijing.jpg");
        const rs = fs.createReadStream(filePath);
        //設定強制快取
        res.set("Cache-Control", "max-age=10000")
        rs.pipe(res);
    })
    app.listen("3000", (err) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log("服務已經啟動  http://127.0.0.1:3000");
        exec("start http://127.0.0.1:3000")
    })