How do you clear cache?

Hello. I’m creating an API using cloud flare workers. It returns a JSON response. However, when the workers site is visited the same JSON response is returned even though I have a math.random function changing it. When I clear the browser cache, I get different response (which is intended and my goal).

How can I have the cache cleared to return a different response on every refresh (without manually having to clear cache)?

Cloudflare does not cache json files by default.

If you are using fetch, maybe the origin server is sending a Header with Cache-Control

let response = await fetch(url)

//response headers are immutable, so you need to declare a new response
response = new Response(response.body, response)

response.headers.set("Cache-Control", "max-age=0")

return response;

Hello @escribeme, I am not fetching anything. Please advise a solution.

addEventListener('fetch', event => {
 event.respondWith(handleRequest(event.request))
})
const headers = {
   'Access-Control-Allow-Origin': '*',
   'Content-type': 'application/json'
 }
var myArray = [
"Apples",
"Bananas",
"Pears"
];
//let cache = caches.default
 
var randomItem = myArray[Math. floor(Math. random()*myArray. length)]
const ping = `{"fruit":"${randomItem}"}`
console.log(randomItem)
/**
* Respond to the request
* @param {Request} request
*/
const body = "hi"
async function handleRequest(request) {
 
   return new Response(ping, { headers }, {status: 200})
   cache.delete(request)
 
}
console.log("hello")

You have placed the randomization inside the global scope (which means it will persist) and your sample size is way too small, so yes, you’re going to get the same responses back.

addEventListener('fetch', event => {
 event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Content-type': 'application/json'
  }
  var myArray = [
  "Apples",
  "Bananas",
  "Pears",
  "Carrots",
  "Cucumbers",
  "Oranges"
  ];
  //let cache = caches.default
  
  var randomItem = myArray[Math. floor(Math. random()*myArray. length)]
  const ping = `{"fruit":"${randomItem}"}`
  console.log(randomItem)
  /**
  * Respond to the request
  * @param {Request} request
  */
  const body = "hi"
  
  return new Response(ping, { headers }, {status: 200})
  cache.delete(request)
 
}

This makes sense. How would I create a new route to serve different API requests? For example I could go to: /fruits which would return a random fruit name and /colors which would return a random color name:

You´ll need to use the URL constructor to get the pathname from the request.url.

const handleRequest = async (event) => {
	const {request} = event
	const url = new URL(request.url)
	const path = url.pathname.split('/').filter(i => i) || []
	
	const ramdom = Math.random();
	
	let data = {
		fruits: ["Apples", "Bananas", "Pears", "Carrots", "Cucumbers", "Oranges"],
		color: ["red", "yellow"]
	}


	if(data.hasOwnProperty(path[0]))
	{
		return new Response(JSON.stringify({
			[path[0]]: data[path[0]][Math.floor(ramdom * data[path[0]].length)]
		}))		
	}
	
	return new Response('bad equest', {status: 400})
}

There’s also a many router components on Github that you can use, but then you also need to use wrangler.

Unfortunately due to technical issues I can’t use wrangler

I don’t want to link it with data, how do I create an entirely different route where I can then serve a different response?

If you can´t use Wrangler, you can still create a new route and Worker from the Dashboard.

Cloudflare -> Select a Domain -> Workers tab

Hi, that’s not something what I am trying to acomplish. How do I create a new route directly in the worker to serve different API requests from? The above code provided doesn’t work.

In my preview example find the const path.

path is an array that contains all the items of the pathname.

If the request has the following url https://example.com/api/posts/hello-world then:

//path[0] = 'api'
//path[1] = 'posts'
//path[2] = 'hello-world'

if(path[0] === 'api')
{
return new Response(' you are in /api')
}

1 Like