Sam Sirry
Sam Sirry

Reputation: 772

Cloudflare worker: How to modify a response body like a string?

I'm trying to detect some string in the response body just to log a message to the console. In another part of the code I also try to replace a piece of text in the response body.

These two attempts are throwing errors in the worker:

   if (response.body.includes("X")) {
        console.log(response.body);
   }

And:

    responseCopy = new Response(response.body, response)
    responseCopy.body = responseCopy.body.replace("x", "y")

How can I:

  1. Check for the existence of a piece of text in the response body and act accordingly?
  2. Manipulate the response body like a string, e.g. replace a string, or overwrite it completely?

P.s. I'm really not that keen with js. I can't understand why it's not working.

Thank you

Upvotes: 2

Views: 2699

Answers (1)

Sam Sirry
Sam Sirry

Reputation: 772

After researching more, I found out I have to make the function (in which the code is running) async, and then await on the response. Only then the text property of the response (not the body (why?)) contains the body text:

    var html = await response.text()

    // Simple replacement regex
    html = html.replace(/x/g , 'y')
    // return modified response
    return new Response(html, response)

Also, the regex replacement should be used, otherwise only the first encounter of the search string is replaced (why js, why?!!).

Upvotes: 4

Related Questions