Reputation: 772
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:
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
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