首页>文档>边缘计算>从指定URL获取JSON并返回

从指定URL获取JSON并返回

// 示例 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));
});
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
搜索