All Products
Search
Document Center

CDN:Request a web page and return page content to the client

Last Updated:Oct 16, 2023

This topic provides sample code that shows how to request a web page and return page content to the client.

Sample code

/**
 * The sample code shows how to request the web page https://www.aliyundoc.com/index.html and return page content to the client.
 * Replace someHost and url with your host and URL addresses during the test.
 */
const someHost = "https://www.aliyundoc.com/"
const url = someHost + "index.html"
/**
 * Use gatherResponse to obtain the response body and return it to the client as a string.
 * Use await gatherResponse(..) in an asynchronous function to ensure that the response body is obtained.
 */
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(request) {
  const init = {
    headers: {
      "content-type": "text/html;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(event.request))
})

Result

A request to fetch the content of the page https://www.aliyundoc.com/index.html is sent in EdgeRoutine and the content is returned to the client.