Created
May 2, 2022 11:16
-
-
Save reggeenr/5567290793a1a455984bc6646fa79ca8 to your computer and use it in GitHub Desktop.
This code snipped can be used to create a Cloudflare Edge Function that directs all requests to an IBM Cloud Code Engine application
This file contains 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) => { | |
const mutable_request = new Request(event.request); | |
event.respondWith(directRequestToCodeEngineApp(mutable_request)); | |
}); | |
async function directRequestToCodeEngineApp(request) { | |
// FQDN of the Code Engine application that should receive the traffic | |
const targetHost = '<app-name>.<randomcharacters>.<region-name>.codeengine.appdomain.cloud'; | |
try { | |
const url = new URL(request.url); | |
// let the code engine know what origin the request came from | |
request.headers.set('X-Forwarded-Host', url.hostname); | |
request.headers.set('host', targetHost); | |
// override the hostname | |
url.hostname = targetHost; | |
// enforce HTTPS towards Code Engine | |
url.protocol = "https:"; | |
// pass the request to the application running on Code Engine | |
return await fetch(url.toString(), request); | |
} catch (error) { | |
// in case of an error, play the regular request | |
console.log(`Failed to pass reqzest to '${targetHost}'`, error); | |
return await fetch(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My original comment was that "This snippet only support requests that don't include a body. It fails for patch and post." but I don't know what I changed but it is working now without any change.