微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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));
,

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。