> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/asp-net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/asp-net/chapter3rest-api-design-development-and-management/33designing-rest-api/331028-demo-api-caching-using-cache-control-directives.md).

# 3.3.10. Demo - API Caching using Cache-Control Directives

* Requirements
  * [Visual studio code](https://code.visualstudio.com/docs/?dv=win)
  * [node.js](https://nodejs.org/en/)
  * [source code from github](https://github.com/acloudfan/REST-API-CACHING)
    * 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)
                    }
                })
      ```
