Skip to content

Instantly share code, notes, and snippets.

@viggy28
Created April 19, 2021 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viggy28/522c4ed05e2bec051d3838ebaff27258 to your computer and use it in GitHub Desktop.
Save viggy28/522c4ed05e2bec051d3838ebaff27258 to your computer and use it in GitHub Desktop.
An example to fetch an URL using Cloudflare workers
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