請求聚合
更新時間 2023-12-04 20:31:31
最近更新時間: 2023-12-04 20:31:31
分享文章
本文介紹如何通過邊緣函數聚合多個請求響應。
向兩個URL發送GET請求,并將響應聚合為一個響應。
示例代碼
// 提取抓取頁面的 <title> 文本內容
async function parseTitleFromHTML(response) {
let htmlText = await response.text()
const titleStart = htmlText.indexOf('<title>');
const titleEnd = htmlText.indexOf('</title>', titleStart);
if (titleStart !== -1 && titleEnd !== -1) {
return htmlText.substring(titleStart + '<title>'.length, titleEnd);
}
return ""
}
async function handleRequest() {
// 同時發出兩個 fetch 請求獲取兩個頁面的 HTML
const responses = await Promise.all([fetch("//www.daliqc.cn/products/accessone"), fetch("//www.daliqc.cn/products/cdnjs")])
// 將兩個頁面的 <title> 文本內容拼接起來
const results = await Promise.all([
parseTitleFromHTML(responses[0]),
parseTitleFromHTML(responses[1]),
])
// 將拼接后的結果返回
return new Response(results.join(" | "))
}
addEventListener("fetch", event => {
return event.respondWith(handleRequest())
})
示例預覽
返回響應聚合內容。
