Fetch and return a JavaScript file

更新时间: 2026-06-16 21:31:12

Use EdgeRoutine to fetch a JavaScript file from a remote URL and return its contents to the client.

Code

/**
 * This example fetches a JavaScript file from a URL and returns its contents to the client.
 * For testing, replace the 'someHost' value with your own.
 */
const someHost = "https://demo.aliyundoc.com/alipay/qrcode/1.0.3/"
const url = someHost + "qrcode.js"
/**
 * The gatherResponse function asynchronously reads the entire response stream.
 * It handles different content types by parsing JSON, reading text, or returning a blob for other formats.
 * Use `await` when calling this function to ensure the entire response body is processed.
 */
async function gatherResponse(response) {
  const headers = response.headers
  const contentType = headers.get("content-type") || ""
  if (contentType.includes("application/json")) {
    return JSON.stringify(await response.json())
  } else if (contentType.includes("application/text")) {
    return response.text()
  } else if (contentType.includes("text/html;charset=UTF-8")) {
    return response.text()
  } else {
    return response.blob()
  }
}

async function handleRequest() {
  const init = {
    headers: {
      "content-type": "application/json;charset=UTF-8",
    },
  }
  const response = await fetch(url, init)
  const results = await gatherResponse(response)
  return new Response(results, init)
}

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

Result

EdgeRoutine fetches the file at https://demo.aliyundoc.com/alipay/qrcode/1.0.3/qrcode.js and returns the response to the client.

请求

上一篇: Request a web page and return page content to the client 下一篇: Perform A/B testing