Cloudflare worker: How to modify a response body like a string? - cloudflare-workers
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:
Check for the existence of a piece of text in the response body and act accordingly?
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
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?!!).
Related
Get same html body in different requests
I'm calling HTTP requests on the same URL multiple times. But every time I get a different body. What's the reason behind that. And what should I do? main() async { for (var i = 0; i < 10; i++) { print(await getBody('https://google.com')); } } Future<String> getBody(String lyricsUrl) async { final response = await http.get(Uri.parse(lyricsUrl)); return response.body.length.toString(); } Here is the output
Basically what you are printing is the length of complete text obtained from the request. So, this includes lot of things like : html code of website which include the body of the page, other text on the page, js functions , etc.. These all would be same for each request you make. But the request also returns a set of parameters like KEI, KEXPI strings which are part of the script for windows.google.. So, if you try printing the complete request text instead of the length alone, you would observe something like below whose values are different for different requests. Thus this is cause of different lengths for different requests. window.google={kEI:\'dzPQYPiJ4fs6rTzssOTwAk\', kEXPI:\'0,772215,1,52320,56873,954,5105,206,4804,2316,383,246,5, 23,5250,16232,10,1106274,1197730,522,31,328984,51224,16114,28684, 17572,4859,1361,9290,3027,3891,13691,4020,978,13228,3847,10622, 1141,7509,2,276,4516,2778,919,5081,885,710,1277,2212,530,149,1943, 6297,108,3406,606,2023,1777,520,12370,603,2624,1989,856,7,5599, 6755,5096,7539,338,4928,108,3407,908,2,231,2614,2397,1027,6441, 3277,3,576,1014,1,54423,149,5990,5333,991,1661,4,1528,2304,1236, 5803,74,1983,2626,2015,1300,2767,7434,3824,3050,2658,872,3291,80,56, 462,2595,31,13628,2305,639,7079,10535,665,2521,3261,2575,2047,2047, 17,3121,6,908,3,3541,1,14710,1814,283,38,351,2,1,3,517,5992,6754, 432,552,4788,2,1394,1498,35,1273,1715,2,3037,20,483,1534,3244,297, 10,147,1067,3,33,3,1343,1461,3271,626,158,254,494,1454,923,93,545, 2,1784,115,1159,1076,262,2834,406,2091,1606,1784,1975,287,1678,2, 445,595,1160,2292,775,1628,2,2003,176,37,1228,756,1526,2,230,206, 4420,519,2,338,204,3,75,50,895,1368,138,2205,116,246,54,269,54,16, 1448,320,2005,61,531,619,223,168,74,262,256,207,87,1,233,341,552, 156,700,2,2,5,79,339,1220,683,590,188,657,2,1,533,461,18,6,304,113, 332,192,270,5629329,194,32,63,155,2,59,5996289,520,47,2800650,2382, 444,1,2,80,1,1796,1,9,2,2551,1,889,795,2,561,1,4265,1,1,2,1331,3299, 843,2609,155,17,13,72,139,4,2,20,2,169,13,19,46,5,39,96,548,29,2, 2,1,2,1,2,2,7,4,1,2,2,2,2,2,2,353,422,91,5,114,43,14,25,43,2,1,4, 1,10,8,1,23952292,4010273,268,1835,26467,2,2374,3,120,3,6,338,3, 2340,74,540\', kBL:\'bsXf\'}; In short, the response text involve various other dynamic values along with the static data on the website. So the length varies from request to request. Feel free to add a comment you still have any doubt or Upvote my answer so that it would be useful..
How to stop ASP .NET from JSONifying JSON
I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api). How can i get it so asp does not jsonify the string
You can write your json data directly to response and set right content headers. public HttpResponseMessage GetData() { var json = "\"value\": \"da\\ta\""; var resp = Request.CreateResponse(HttpStatusCode.OK); resp.Content = new StringContent(json); resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API return resp; }
How can I catch a pound sign(#) from URL with multiple values in ASHX files
This is my ASHX File where I am catching multiple parameters from request URL using httpcontext, and it is working properly but when I am including a Hash(#) value in Text parameter through the URL. It is not taking the value of FLOW which is another parameter(next to Text parameter). So it is working for: http://localhost:10326/ussd.ashx?user=MSL&pass=MSL663055&tid=65506&msisdn=8801520101525&text=***3333**&flow=begin&momt=mo And it is not working for: http://localhost:10326/ussd.ashx?user=MSL&pass=MSL663055&tid=65506&msisdn=8801520101525&text=***3333#**&flow=begin&momt=mo My ASHX files: public void ProcessRequest(HttpContext context) { HttpRequest httpRequest = context.Request; string user = httpRequest.QueryString["user"].ToString(); string pass = httpRequest.QueryString["pass"].ToString(); string tid = httpRequest.QueryString["tid"].ToString(); string msisdn = httpRequest.QueryString["msisdn"].ToString(); string text = httpRequest.QueryString["text"].ToString(); flow = httpRequest.QueryString["flow"].ToString(); HttpContext.Current.Session["user"] = user; HttpContext.Current.Session["pass"] = pass; HttpContext.Current.Session["tid"] = tid; HttpContext.Current.Session["msisdn"] = msisdn; HttpContext.Current.Session["text"] = text; HttpContext.Current.Session["flow"] = flow;
You need to URI encode your parameter values before they are added to the URL. This way the server will not get confused by unsafe characters such as '#' which has its own meaning when included as part of a URL. See RFC 3986 Section 2. See Encode URL in JavaScript as an example of how to encode the sent data using JavaScript. Whatever is sending the data in the URL will need to do the encoding. There is not much you can do once the request has reached the server. Without knowing how your URL is being created, I can't offer much more. In short: the problem is with your client code not your ASHX file.
How do i check whether the url is responsive or not
I have Image Url in my Database and i want to check whether the URL is responsive or not in the browser . please Help me . For Example : http://images.jactravel.co.uk/6008_1_1.jpg or http://images.jactravel.co.uk/6049_2_4.jpg now how can i check automatically this url is responsive or not
I assume that by responsive you mean whether you can get a response when you call a specific URL or not. To do that without actually downloading the content, you can use the HttpClient.GetAsync(string,HttpCompletionOption) with an HttpCompletionOption of ResponseHeadersRead. This will make GetAsync return immediately with a status code (eg 200, 404 or 500) without waiting to download the entire content, eg: using (var client = new HttpClient()) { using(var response = await client.GetAsync("http://mysite/myimage.jpg", HttpCompletionOption.ResponseHeadersRead)) { if (response.IsSuccessStatusCode) { //The URL is good } } } To actually read the content, you need to access one of the Read methods of the response's Content property. For example, you can use the CopyToAsync to copy the content to a file stream, or use ReadAsByteArrayAsync to read the content as a byte array, eg: var buffer=await response.Content.ReadAsByteArrayAsync();
Is there a way to send back a string as well as an image via Http response?
I am hitting a servlet and based on the data passed to the server , I have two conditions. 1) If data is 'X' then I have to return a string in response. 2) If data is 'Y' then I have to return a string as well an image in response. So is this scenario possible? How do I return both a string as well as image from the server? Any suggestions are welcome.
Simply return the URL of the image and store it in the session object, something like this: String imgUrl = "...URL"; request.getSession.setAttribute("Image", imgUrl); Then call the requestDispatcher and forward it to a jsp, so request.getRequestDispatcher("jsp/myJsp").forward(req, resp); Then, from the JSP extract the imgUrl, <% String url = (String)session.getSession.getAttribute("Image"); and there you go. Good luck!