文档中心 边缘应用 搭建边缘静态网站

搭建边缘静态网站

更新时间:2023-11-30 11:03:30

本章示例为通过【边缘KV】+【边缘函数】,搭建一个静态网站,页面内容包括:图片、文字、视频等。
代码说明:『边缘KV』负责存储网站资源,『边缘函数』负责资源路由与业务逻辑。

详细代码

/* 
 *EdgeKV中是以如下形式存储数据的:
 *| KEY            | VALUE        |
 *| -------------- | ------------ |
 *| /index.html    | 相应文件数据   |
 *| /img/about.jpg | 相应文件数据   |
 *假设请求 url 为:http://www.test.com/catalog-z/index.html
 *我们取末尾的文件名 /index.html 作为 key,就可以拿到这个文件的数据了 
 */
async function handleRequest(request) {
    // 从 url 中取得所请求的文件名
    let {pathname} = new URL(request.url.toLowerCase())
    if (pathname.endsWith('/'))  pathname = pathname.substring(0, pathname.length - 1)
    pathname = pathname.substring("/catalog-z".length)
    if (pathname === '') pathname = '/index.html'

    // 以文件名为 key 从 EdgeKV 中取出文件内容,注意 namespace 是我们之前上传文件所用的那个 catalog-z
    const kv = new EdgeKV({namespace: "catalog_z2"})
    const content = await kv.get(pathname, {type: "stream"})
    if (content == null) {
        return new Response("Page not found", {status: 404}) // 没取到文件响应404
    }

    // 将取到的文件响应给客户端
    const contentType = contentTypeOfFile(pathname) // 根据文件名设置Content-Type
    const headers = { 'Content-Type': contentType, 'Cache-Control': 'max-age=180' }
    console.log(`请求文件名:${pathname},类型为:${contentType}`) 
    return new Response(content, {headers: headers})
}

function contentTypeOfFile(fileName) {
    const ext = fileName.split('.').pop()
    switch (ext) {
        case 'html':    return 'text/html'
        case 'css':     return 'text/css'
        case 'js':      return 'application/javascript'
        case 'jpg':     return 'image/jpeg'
        case 'png':     return 'image/png'
        case 'mp4':     return 'video/mp4'
        case 'eot':     return 'application/vnd.ms-fontobject'
        case 'svg':
        case 'svgz':    return 'image/svg+xml'
        case 'woff':    return 'font/woff'
        case 'woff2':   return 'font/woff2'
        default:        return 'application/octet-stream'
    }
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})

注:边缘网站有下列优势,1. 无服务器、分布式部署,不需要各种传统源站成本;2. 版本上线,更新快;3.就近访问,时延低。

本篇文档内容对您是否有帮助?
有帮助
我要反馈
提交成功!非常感谢您的反馈,我们会继续努力做到更好!