本文介紹請求一個頁面並返回樣本情境及結果。
代碼
/**
* 樣本為請求https://www.aliyundoc.com/index.html並返回
* 測試是請將url和someHost替換為您自己的地址
*/
const someHost = "https://www.aliyundoc.com/"
const url = someHost + "index.html"
/**
* gatherResponse函數將response處理成string並返回
* 在1個非同步函數中使用await gatherResponse(..)確保完整拿到response的body
*/
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))
})結果
ER發出fetch子請求,得到https://www.aliyundoc.com/index.html 的內容並返回給用戶端。