直接从 Google 云存储服务 html 并解析相关链接

Serve html directly from Google Cloud Storage and resolve relative links

我有一个简单的 html 文件,其中包括 css 这样的:

<link rel="stylesheet" href="./css/style.css" />

我上传了这个html文件和css文件google云存储,并设置权限public。

在我用 node js 编写的应用程序中,我想在用户访问我的根页面时提供这个 html 文件。

在我的应用程序中,我有以下代码:

public async getPublicFile(opts: IGetFileOpts): Promise<File> {
    const bucket = this.storage.bucket(opts.bucket);

    return bucket.file(path.join(opts.type, opts.fileName));
}

@Get()
public async serveFile(@Res() response: Response) {
    const file = await this.storageService.getPublicFile({
        organization: organization,
        fileName: 'index.html',
        type: 'resources',
    });

   file.createReadStream().pipe(response);
}

这按预期工作。它将从桶中服务器 index.html。但是,由于此 html 文件与 css 文件有相对的 link,它不会加载 css 文件,因为找不到它。

我该如何解决这个问题,以便 css 文件也能被提供?目前我在本地计算机上 运行,但它将部署到 Google Compute Engine。

我为 AppEngine https://cloud.google.com/appengine/docs/standard/go/serving-static-files

找到了这个 link

在 AppEngine 中,我可以像这样定义一些处理程序:

handlers:
  - url: /favicon\.ico
    static_files: favicon.ico
    upload: favicon\.ico

  - url: /static
    static_dir: public

  - url: /.*
    secure: always
    redirect_http_response_code: 301
    script: auto

但据我所知,这在本地机器上不起作用。

另外,电子商务公司如何解决这个问题?例如,每个商店都可以有不同的可定制主题。所以我知道每个租户都有自己的存储桶,在租户存储桶中,这个可定制的主题保存正确吗?所以我如何假设应该像我一样有类似的问题。对于这种情况,他们是如何应对和处理的?

您当前正在尝试从 index.html 服务于您的 google 应用程序引擎 url.这不能开箱即用。

有很多选项可以解决这个问题:

  • 从 public 中的同一个存储桶中为您的 index.html 提供服务,您的其他静态文件如 css 在哪里。这也有蜂作为 CDN 的好处,效率更高。 (如果可能的话,这是我推荐的方式,唯一你不能这样做的情况可能是当你想在将 index.html 文件发送回客户端之前计算服务器端 html 东西时,但是有这很有可能在客户端完成)

  • 在 index.html“动态”或“静态”中为您的 css 资源构建绝对路径,因此 link 标记可能如下所示:

<link rel="stylesheet" href="https://bucketurl.com/css/style.css" />
  • 使用特殊路径以编程方式为您的应用程序提供所有内容,该路径将通过读取存储桶中的文件来提供静态内容,就像您使用 index.html 一样。这应该可以让您保留其他静态文件的相对路径。