JSON caching with Cloudflare

I am developing a backend system for my application on the Google App Engine.

My application server and backend interact with json. Like http://server.example.com/api/check_status/3838373.json or just http://server.example.com/api/check_status/3838373/

And I plan to use CloudFlare to cache JSON pages.

Which should I use for the headline?

Content-type: application/json
Content-type: text/html

Is CloudFlare a cache of my server responses to reduce my costs? Because I will not use CSS, image, etc.

+6
source share
2 answers

Cloudflare ( ) /, , , . - ( *.html) JSON. URL (, .jpg?) Content-Type.

, , URL-, Cache Everything .

http://blog.cloudflare.com/introducing-pagerules-advanced-caching

BTW HTML Content-Type JSON.

+14

( 5 ) :

: Cloudflare (, , - ).

: "I just want to add.json to the list of static extensions". , , JSON - - . , , - 60 5 , , , , .

, .json .json:

// Note: there could be tiny cut and paste bugs in here - please fix if you find!
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event)
{
  let request = event.request;
  let ttl = undefined;
  let cache = caches.default;      
  let url = new URL(event.request.url);

  let shouldCache = false;


  // cache JSON files with custom max age
  if (url.pathname.endsWith('.json'))
  {
    shouldCache = true;
    ttl = 60;
  }

  // look in cache for existing item
  let response = await cache.match(request);

  if (!response) 
  {       
    // fetch URL
    response = await fetch(request);

    // if the resource should be cached then put it in cache using the cache key
    if (shouldCache)
    {
      // clone response to be able to edit headers
      response = new Response(response.body, response);

      if (ttl) 
      {
        // https://developers.cloudflare.com/workers/recipes/vcl-conversion/controlling-the-cache/
        response.headers.append('Cache-Control', 'max-age=' + ttl);
      }

      // put into cache (need to clone again)
      event.waitUntil(cache.put(request, response.clone()));
    }

    return response;
  }

  else {
    return response;
  }
}

MIME- , , , , API.

, - . products-1.json/products-2.json max-age .

0

All Articles