如何使用 Javascript 修改响应替换字符串?

问题描述

以下 Javscript(在 Cloudflare Workers 中运行)做了两件事:

  1. 它允许我用我的域 satchel.id 替换 domain.com(这有效)
  2. 添加代码以将“satchel.id”替换为“domain.com”——这不起作用
    /** 
     * 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))
    })

解决方法

.json() 会解析一个 JSON 格式的响应字符串,但它通常不会给你一个字符串作为回报,而 .replaceAll 只能用于字符串。我想您可以将对象字符串化,然后将其转换回 JSON:

const result = await originalResponse.json()
const replacedResultJSON = JSON.stringify(result).replaceAll("domain.com","satchel.id");
return Response(JSON.parse(replacedResultJSON));
,

最初上面的代码没有按预期运行。但现在确实如此。