Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

httpresponse - How can I modify the Response (substituting strings) using Javascript?

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))
    })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...