简体   繁体   中英

Cloudflare Workers main URL Redirect not working, Params as well

Alief here. I'm trying to use Cloudflare Workers to redirect a subdomain to a different domain, but it's not working : wa.example.com to wa.me/60123456789

And its path, which works well : wa.example.com/WantToBuy to wa.me/60123456789?text=Want%20To%20Buy

Also, I'm unable to remove params (fbclid) from the subdomain in the same script.

The route for this worker is wa.example.com/*

How do I make it work? Thank you in advance.

Here is my full script:

addEventListener('fetch', event => {
  event.respondWith(fetchAndApply(event.request))
})

async function fetchAndApply(request) {

let url = new URL(request.url);
let path = url.pathname;

var yourNumber = "60123456789"
const yourMessage = "'"+path+"'"

  number = yourNumber
  message = yourMessage.match(/(\d+|[a-z]+|([A-Z]([A-Z]+|[a-z]*)))/g).join('%20')

let whatsapp = 'wa.me/' + number + '?text=' + message

return fetch(whatsapp,request);
}

addEventListener('fetch', event => {
  let url = new URL(event.request.url)

  if (url.searchParams.has('fbclid'))
   url.searchParams.delete('fbclid')

  event.respondWith(
    fetch(url, event.request)
  )
})

Several problems here...

number = yourNumber
message = yourMessage.match(/(\d+|[a-z]+|([A-Z]([A-Z]+|[a-z]*)))/g).join('%20')

You should put var or let before these declarations of number and message . Otherwise, you are storing these into global variables, which could affect other requests, which is almost certainly not what you want.

message = yourMessage.match(/(\d+|[a-z]+|([A-Z]([A-Z]+|[a-z]*)))/g).join('%20')

When match() doesn't find any matches, it returns null . When you then call .join() on it, this will throw an exception. Indeed, running your script in the preview generates this error message in the console: Uncaught (in response) TypeError: Cannot read property 'join' of null

This is why your script isn't working when no path is sent -- in that case, there are no matches of the regex.

let whatsapp = 'wa.me/' + number + '?text=' + message

You probably want to add https:// to the beginning of this URL, otherwise it's not valid.

addEventListener('fetch', event => {

Your script uses addEventListener('fetch') more than once, with both listeners producing a result. The first listener that calls respondWith() will "win", so the second listener is ignored, hence why you find it isn't working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM