Build a URL Shortener with Cloudflare Workers & KV

Source code GitHub: https://github.com/crazypeace/Url-Shorten-Worker

In localStorage, only write the random string of the short URL

Omitted


No need to use
    wrapping
  • for displaying the urlList. Change to

wrapping

Omitted


When displaying the short URL, add a delete button in front

First turn off auto-loading localStorage, then try writing it in the HTML to see the effect.

     
      some text
     
      some text some text some text some text some text some text some text some text some text some text some text

API supports deleting short URLs

POST adds fields

cmd: value add, del;

keyPhrase: when adding, it's a custom short URL; when deleting, it's the short URL specified for deletion.


For the part displaying the urlList, add an onclick event inside the button

   
    some text
   
    some text some text some text some text some text some text some text some text some text some text some text

Tested the effect, it works and modifies the KV


The part that loads localStorage to the urlList, implement it with JS

function addUrlToList(shortUrl, longUrl) {
  let urlList = document.querySelector("#urlList")

  let child = document.createElement('div')
  child.classList.add("list-group-item")

  let btn = document.createElement('button')
  btn.setAttribute('type', 'button')
  btn.classList.add("btn", "btn-danger")
  btn.setAttribute('onclick', 'deleteShortUrl(\"' + shortUrl + '\")')
  btn.innerText = "X"
  child.appendChild(btn)

  let text = document.createElement('span')
  text.innerText = window.location.host + "/" +shortUrl + " " + longUrl
  child.appendChild(text)

  urlList.append(child)
}

Standardize the API

When the API fails to add a short URL, the status is not 200, and the error message should not be placed in the key; the error should be stored separately.

When the API successfully adds a short URL, the status is 200, and the key is simply the key field of the short URL, without the '/ ' prefix.

When displaying the API result, it should first check whether the status is 200 (success), and then decide whether to display the key short URL or display the error message.

Omitted


Comments