Created
April 19, 2021 01:26
-
-
Save viggy28/522c4ed05e2bec051d3838ebaff27258 to your computer and use it in GitHub Desktop.
An example to fetch an URL using Cloudflare workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener("fetch", event => { | |
return event.respondWith(handleRequest()) | |
}) | |
async function handleRequest() { | |
const init = { | |
"headers": { | |
"x-rapidapi-key": "<replaceme>", | |
"x-rapidapi-host": "community-open-weather-map.p.rapidapi.com" | |
}, | |
} | |
const response = await fetch("https://community-open-weather-map.p.rapidapi.com/weather?q=London%2Cuk&lat=0&lon=0&callback=test&id=2172797&lang=null&units=%22metric%22%20or%20%22imperial%22&mode=xml%2C%20html", init) | |
const results = await gatherResponse(response) | |
return new Response(results, init) | |
} | |
/** | |
* gatherResponse awaits and returns a response body as a string. | |
* Use await gatherResponse(..) in an async function to get the response body | |
* @param {Response} response | |
*/ | |
async function gatherResponse(response) { | |
const { headers } = response | |
const contentType = headers.get("content-type") || "" | |
if (contentType.includes("application/json")) { | |
return JSON.stringify(await response.json()) | |
} | |
else if (contentType.includes("application/text")) { | |
return await response.text() | |
} | |
else if (contentType.includes("text/html")) { | |
return await response.text() | |
} | |
else { | |
return await response.text() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment