3.3.10. Demo - API Caching using Cache-Control Directives

  • Requirements

  • 程式碼解析

    • 1.API provider 設定max-age

      • 當cache expired前, browser的請求都不會到backend, 因此counter不會增加

      • cache

        app.get('/cachetest', function (req, res) {
          // Set the headers
          res.header('Cache-Control', 'public, max-age='+MAX_AGE);
        
          // Increment the counter
          counter++
          console.log('recvd ' + counter)
        
          // Response data
          data = {
              value: "Hello Cache !!!",
              counter: counter
        };
          res.send(JSON.stringify(data));
        });
    • 2.Client 設定no-cache

      • 會取得新的資料

        $.ajax(
                  {
                      type:'GET',
                      url: "http://localhost:3000/cachetest" ,
                      headers: {"Cache-Control" : "no-cache"},
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType:  "json",
                      success: success ,
                      error: function (msg, url, line) {
                          alert('error '+msg+ "    "+url+"    "+line)
                      }
                  })

Last updated