Cloudflare Workers-带有Vuejs的SPA

时间:2019-10-17 12:09:43

标签: vue.js cloudflare cloudflare-workers

您好,我已使用以下命令将Vue.js应用程序部署到Cloudflare工作者:

wrangler generate --site
wrangler publish --env dev

这是我的wrangler.toml:

account_id = "xxx"
name = "name"
type = "webpack"
workers_dev = true

[site]
bucket = "./dist"
entry-point = "workers-site"

[env.dev]
name = "name"
route = "xxx.com/*"
zone_id = "XXX"
account_id = "XXX"

该网站很好,并且位于“ xxx.com”上,但是当我在其他任何路线上刷新页面时,都会收到此错误消息:

  

在内容名称空间中找不到es-es / index.html

例如:

  

在您的内容名称空间中找不到category / 65 / index.html

在nginx上,我必须创建一个.htaccess,但是我不知道如何使它在这里工作。

如果有帮助,这是我的index.js:

import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'

/**
 * The DEBUG flag will do two things that help during development:
 * 1. we will skip caching on the edge, which makes it easier to
 *    debug.
 * 2. we will return an error message on exception in your Response rather
 *    than the default 404.html page.
 */
const DEBUG = false

addEventListener('fetch', event => {
  try {
    event.respondWith(handleEvent(event))
  } catch (e) {
    if (DEBUG) {
      return event.respondWith(
        new Response(e.message || e.toString(), {
          status: 500,
        }),
      )
    }
    event.respondWith(new Response('Internal Error', { status: 500 }))
  }
})

async function handleEvent(event) {
  const url = new URL(event.request.url)
  let options = {}

  /**
   * You can add custom logic to how we fetch your assets
   * by configuring the function `mapRequestToAsset`
   */
  // options.mapRequestToAsset = handlePrefix(/^\/docs/)

  try {
    if (DEBUG) {
      // customize caching
      options.cacheControl = {
        bypassCache: true,
      }
    }
    return await getAssetFromKV(event, options)
  } catch (e) {
    // if an error is thrown try to serve the asset at 404.html
    if (!DEBUG) {
      try {
        let notFoundResponse = await getAssetFromKV(event, {
          mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
        })

        return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
      } catch (e) {}
    }

    return new Response(e.message || e.toString(), { status: 500 })
  }
}

/**
 * Here's one example of how to modify a request to
 * remove a specific prefix, in this case `/docs` from
 * the url. This can be useful if you are deploying to a
 * route on a zone, or if you only want your static content
 * to exist at a specific path.
 */
function handlePrefix(prefix) {
  return request => {
    // compute the default (e.g. / -> index.html)
    let defaultAssetKey = mapRequestToAsset(request)
    let url = new URL(defaultAssetKey.url)

    // strip the prefix from the path for lookup
    url.pathname = url.pathname.replace(prefix, '/')

    // inherit all other props from the default request
    return new Request(url.toString(), defaultAssetKey)
  }
}

2 个答案:

答案 0 :(得分:7)

现在似乎有一种内置的方法可以做到这一点:

import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
...
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })

https://github.com/cloudflare/kv-asset-handler#servesinglepageapp

答案 1 :(得分:4)

如您所知,Vue.js(与许多其他SPA框架一样)期望,对于未映射到特定文件的任何路径,服务器都会退回到提供根/index.html文件的位置。然后,Vue将在浏览器端JavaScript中进行路由。您提到您知道如何使用.htaccess来完成此后备工作,但是我们如何才能与Workers一起完成工作?

好消息:在Workers中,我们可以编写代码来做我们想做的事情!

实际上,工作程序代码已经具有特定的代码块来处理“找不到404”错误。解决该问题的一种方法是更改​​此代码块,以使其返回/index.html而不是返回404错误。

我们要更改的代码是这一部分:

  } catch (e) {
    // if an error is thrown try to serve the asset at 404.html
    if (!DEBUG) {
      try {
        let notFoundResponse = await getAssetFromKV(event, {
          mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
        })

        return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
      } catch (e) {}
    }

    return new Response(e.message || e.toString(), { status: 500 })
  }

我们要将其更改为:

  } catch (e) {
    // Fall back to serving `/index.html` on errors.
    return getAssetFromKV(event, {
      mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/index.html`, req),
    })
  }

应该可以解决问题。


但是,上述解决方案有一个小问题:对于任何HTML页面(除了根目录之外),它将进行两次查找,首先是特定路径,然后才查找/index.html为后备。这些查询的速度非常快,但是也许我们可以变得更聪明一些,并根据URL预先检测HTML页面,从而使事情变得更快。

为此,我们要自定义mapRequestToAsset函数。您可以在代码的注释中看到关于此的提示:

  /**
   * You can add custom logic to how we fetch your assets
   * by configuring the function `mapRequestToAsset`
   */
  // options.mapRequestToAsset = handlePrefix(/^\/docs/)

我们继续使用它。将上面的注释替换为:

  options.mapRequestToAsset = req => {
    // First let's apply the default handler, which we imported from
    // '@cloudflare/kv-asset-handler' at the top of the file. We do
    // this because the default handler already has logic to detect
    // paths that should map to HTML files, for which it appends
    // `/index.html` to the path.
    req = mapRequestToAsset(req)

    // Now we can detect if the default handler decided to map to
    // index.html in some specific directory.
    if (req.url.endsWith('/index.html')) {
      // Indeed. Let's change it to instead map to the root `/index.html`.
      // This avoids the need to do a redundant lookup that we know will
      // fail.
      return new Request(`${new URL(req.url).origin}/index.html`, req)
    } else {
      // The default handler decided this is not an HTML page. It's probably
      // an image, CSS, or JS file. Leave it as-is.
      return req
    }
  }

现在,代码专门检测HTML请求,并将其替换为根/index.html,因此无需浪费时间查找不存在的文件,仅用于捕获导致的错误。对于其他类型的文件(图像,JS,CSS等),代码不会修改文件名。