So I have a pretty normal eventListener that listens to the incoming events.

      addEventListener("fetch", event => {
               event.respondWith(handleRequest(event.request))
      })

It goes to the handleRequest, which does certain different tasks depending on the request.url.

      async function handleRequest (request) {
          var url = new URL(request.url);
          if (url.pathname === '[some-domain-name]/[some-link]') {
              var jsonResult = handleJSON();
              return jsonResult;
          } else {
              return handleHTML();
      }

The handleJSON() and the handleHTML() are two additional functions that I have set up. What I essentially want to do is add one more if condition that has the criteria based on the response from handleJSON(), i.e., if jsonResult = [somevalidvalue] run handleHMTL() else respond with "You haven't accessed /[some-link] yet.

So to summarize, if we go to [some-domain-name] it should respond with the sentence. Then once we access /[some-link] we get some kind of value in jsonResult AFTER WHICH if we go back to [some-domain-name] it should hit with the response from handleHTML(). Also if possible, I'd like to know how can I pass the value from jsonResult in to our handleHTML() function. This is the result in the jsonResult.

           const body = JSON.stringify(links, null, 2)        
           return new Response(body, init)

I'm sorry if the information sounds too long and stretched out. I haven't used Cloudflare's worker before and I've been trying to figure out the little stuff of what goes where and what I can and can't do with it. Thank You!

1

There are 1 best solutions below

0
On

Your code implies that handleJSON() returns a Response object, since you then return it as the response to the original request. Your question is a little unclear, but it sounds like you are saying that this response contains a JSON body, and you want to inspect that body in your code. So you could do something like:

let jsonResponse = handleJSON();
if (jsonResponse.ok) {  // check status code is 200
  let jsonValue = await jsonRespnose.json();
  if (jsonValue.someFlag) {
    return handleHTML();
  }
}

Note that calling jsonResponse.json() consumes the response body. Therefore, you can no longer return the response after this point. If you decide you want to return the JSON response to the client after all, you'll need to reconstruct it, like:

jsonResponse = new Respnose(JSON.stringify(jsonValue), jsonResponse);

This recreates the response body, while copying over the status and headers from the original response.