My worker is BROKEN!

Ok so one of my workers (https://aboutrock2.submarine.workers.dev/) is broken! Basicly, when you click on one the links (“Tormented”, “Dysfunction”, “Break The Cycle”, and “Contact rules”) it shows that it redirects (in the URL, cause it changes) but it never changes the page! It’s like it shows it fetches, but it never does! Here is the worker’s code

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 200 })
    )
  );
});

/**
 * Many more examples available at:
 *   https://developers.cloudflare.com/workers/examples
 * @param {Request} request
 * @returns {Promise<Response>}
 */
async function handleRequest(request) {
  const { pathname } = new URL(request.url);

  if (pathname.startsWith("/api")) {
    return new Response(JSON.stringify({ pathname }), {
      headers: { "Content-Type": "application/json" },
    });
  }

  if (pathname.startsWith("/status")) {
    const httpStatusCode = Number(pathname.split("/")[2]);

    return Number.isInteger(httpStatusCode)
      ? fetch("https://aboutrock2.godaddysites.com/" + httpStatusCode)
      : new Response("That's not a valid HTTP status code.");
  }

  return fetch("https://aboutrock2.godaddysites.com/");
}

Anyone know what I should do? Is there a problem with the code or something?

what do you expect to change… you never actually fetch other pages.

return fetch(“https://aboutrock2.godaddysites.com/”);

You’re fetching https://aboutrock2.godaddysites.com/ and that only. If you want to also use the path then change that to

return fetch(`https://aboutrock2.godaddysites.com${pathname}`);

So that it will add the pathname


Please see docs on request pathname here: URL.pathname - Web APIs | MDN

2 Likes

Where do I add it into the code? Do I just copy the current code then add in the return fetch URL? Or just change the current return fetch URL?

Well, I gave you the code currently there and it fixed. Find waldo :stuck_out_tongue:

2 Likes

No you did not, you just told me what to change it to, I have multiple different URL’s I wish to fetch and I want to know if I change the return URL or add them in (one after the other) or what to do?

I told you to use URL pathname. Where you put it, that’s up to you. I sent the replacement code for where this issue lies.

You can put it where you need to though as it may be relevant in other places and other Workers. So, let’s figure out what it does and where to put it :slight_smile:

Let’s say your domain is example.com and the Worker is mapped to all paths

The first part of this code is the pathname. Now, what is this line? Well, this is known as object destructuring. It’s a way of getting properties from an object. In this case, URL has a property named pathname. Therefore we extract it.

const { pathname } = new URL(request.url);

// Let's say someone went to example.com/blog that means:
// pathname = '/blog'

// If someone went to example.com, any idea what the pathname would be?
// pathname = '/'
// Why / and not an empty string? Well, pathname will always be prefixed with a slash

// If someone went to example.com/blog?id=10 then we know it would be /blog but...
// what about that query param?
// pathname will ignore query params which means:
// pathname = '/blog'

With the understanding of how pathname works, let’s put this into some real context. If I have my website on Pages and I want to use a custom domain (assuming I couldn’t just add it) then I need a Worker to map all requests.

What’s especially important in this case is that every path is the same and goes where it needs to because if a user visits my home page they’re also loading CSS, JS and other such assets.
So, with the understanding of pathname, let’s put that into practice.

Let’s take this code:

const { pathname } = new URL(request.url);

// So, we want to "fetch" our pages.dev domain and return the page
return fetch('https://example.pages.dev');

When someone visits our page we will get let’s say 3 requests to our worker:

  1. / (this will sit at https://example.pages.dev/)
  2. /js/main.js (this will sit at https://example.pages.dev/js/main.js)
  3. /css/main.css (this will sit at https://example.pages.dev/main.css)

So we’re loading the “index” file, a JS file, and a CSS file (these are requested from our HTML index file)

Ok, now what happens when these come into our Worker?

Index: /

return fetch('https://example.pages.dev');
// This will fetch 'https://example.pages.dev'

JS file: /js/main.js

return fetch('https://example.pages.dev');
// This will fetch 'https://example.pages.dev'

CSS file: /css/main.css

return fetch('https://example.pages.dev');
// This will fetch 'https://example.pages.dev'

All of our assets are requesting the same URL (https://example.pages.dev) which will return an HTML page :frowning:

So, how do we fix this? Well, haha! We can go back to that pathname property we had before. Since, we know this will return the path of the request

Let’s take the JS file as an example
JS file: /js/main.js

const { pathname } = new URL(request.url);
// pathname = '/js/main.js'

return fetch('https://example.pages.dev');
// This will fetch 'https://example.pages.dev'

Ok, that’s good! We can get the pathname and it’s correct but… oh no, we’re still getting the HTML page…

Well, young padawan, that’s because we didn’t change our fetch (remember, this is what will send a request to our Pages site). It’s still just fetching the index page!

const { pathname } = new URL(request.url);
// pathname = '/js/main.js'

return fetch('https://example.pages.dev' + pathame);
// This will fetch 'https://example.pages.dev/js/main.js'

haha! Now we’re fetching the JS file! We’re basically adding that pathname (in this case /js/main.js) to our existing URL we’re fetching. This means the resulting URL we’re fetching is https://example.pages.dev/js/main.js - that’s exactly what we want!


Hopefully, you can understand what pathname returns and more importantly, how to use it! :slight_smile:

Here’s some great resources for reference:

3 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.