// 示例 url
const url = 'https://su.baidu.com/preview/index.html';
// 设置 contentType
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get('content-type');
if (contentType.includes('application/json')) {
return await response.json();
} else if (contentType.includes('application/text')) {
return await response.text();
} else if (contentType.includes('text/html')) {
return await response.text();
} else {
return await response.text();
}
}
async function handleRequest(request) {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
};
// 取 html
const response = await fetch(url, init);
// 添加 content-type
const results = await gatherResponse(response);
// 返回结果
return new Response(results, init);
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request));
});
从指定URL获取页面并返回
暂无讨论,说说你的看法吧