The following Javscript (running in Cloudflare Workers) does two things:
- It allows me to substitute my domain satchel.id for domain.com (this works)
- I added code to substitute 'satchel.id' for 'domain.com' -- this doesn't work
/**
* An object with different URLs to fetch
* @param {Object} ORIGINS
*/
const ORIGINS = {
"api.satchel.id": "api.domain.com",
"google.yourdomain.com": "www.google.com",
}
async function handleRequest(request) {
const url = new URL(request.url)
// Check if incoming hostname is a key in the ORIGINS object
if (url.hostname in ORIGINS) {
const target = ORIGINS[url.hostname]
url.hostname = target
// If it is, proxy request to that third party origin
// return await fetch(url.toString(), request)
let originalResponse = await fetch(url.toString(), request)
// return originalResponse
// THIS is the code that is erroring out after trying different things
// This is regarding my STACKOVERFLOW submission:
// https://stackoverflow.com/questions/65516289/how-can-i-modify-the-response-substituting-strings-using-javascript
const originalBody = await originalResponse.json() //Promise
const body = JSON.stringify(originalBody) // Promise as JSON
let newBody = body.replaceAll("domain", "satchel") // replace string
return new Response(newBody, originalResponse)
}
// Otherwise, process request as normal
return await fetch(request)
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…