请求一个页面并返回
本文介绍请求一个页面并返回示例场景及结果。
代码
/**
* 示例为请求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
的内容并返回给客户端。