// 示例 url
const url = 'https://www.example.com/json';
// 设置 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': 'application/json;charset=UTF-8',
},
};
// 取 json
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获取JSON并返回
暂无讨论,说说你的看法吧