Skip to content

Instantly share code, notes, and snippets.

@harishphk
Created October 25, 2020 17:35
Show Gist options
  • Save harishphk/d00bcf2879bea6d890ba4c4b2b039a9f to your computer and use it in GitHub Desktop.
Save harishphk/d00bcf2879bea6d890ba4c4b2b039a9f to your computer and use it in GitHub Desktop.
Use cloudflare as a proxy for your API
async function handleRequest(request) {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET'
},
}
const { searchParams } = new URL(request.url)
let queryParam1 = searchParams.get('queryParam')
const url = 'https://api.domain.com' + queryParam1
const response = await fetch(url, init)
const jsonBody = await response.json()
JSONresponse = JSON.stringify(jsonBody, null, 2)
return new Response(api, init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment