3.3.10. Demo - API Caching using Cache-Control Directives
Requirements
1.clone repository
git clone https://github.com/acloudfan/REST-API-Course.git cd REST-API-CACHEING/ npm install
程式碼解析
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) } })
Previous3.3.9.API Caching (2 of 2) Concepts & Design decisionsNext3.3.11.Building support for Partial Responses
Last updated
Was this helpful?