2

The following Javscript (running in Cloudflare Workers) does two things:

  1. It allows me to substitute my domain satchel.id for domain.com (this works)
  2. 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))
    })
Satchel
  • 15,436
  • 22
  • 100
  • 180

2 Answers2

0

.json() will parse a response string in JSON format, but it usually won't give you a string in return, and .replaceAll can only be used on strings. I suppose you could stringify the object, then turn it back into JSON:

const result = await originalResponse.json()
const replacedResultJSON = JSON.stringify(result).replaceAll("domain.com", "satchel.id");
return Response(JSON.parse(replacedResultJSON));
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
0

Originally the above code didn't behave as expected. But now it does.

Satchel
  • 15,436
  • 22
  • 100
  • 180