Skip to content

提供单页应用程序服务

Ktor 提供了提供单页应用程序服务的能力,包括 React、Angular 或 Vue。

添加依赖项

要提供单页应用程序服务,您只需要 ktor-server-core 依赖项。 不需要任何特定的依赖项。

提供应用程序服务

要提供单页应用程序服务,您需要定义希望从何处提供内容:本地文件系统或 classpath。 您至少需要指定一个包含单页应用程序的文件夹/资源包。

提供特定框架的应用程序服务

您可以提供使用特定框架(例如 React、Angular、Vue 等)创建的单页应用程序构建版本。 假设我们的项目根目录中有一个包含 React 应用程序的 react-app 文件夹。 该应用程序具有以下结构,并将 index.html 文件作为主页面:

text
react-app
├── index.html
├── ...
└── static
    └── ...

要提供此应用程序,请在 routing 块内调用 singlePageApplication,并将文件夹名称传递给 react 函数:

kotlin
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.routing.*

fun Application.module() {
    routing {
        singlePageApplication {
            react("react-app")
        }
    }
}

Ktor 会自动查找 index.html。 要了解如何自定义默认页面,请参阅自定义服务设置

对于其他框架,请使用相应的函数,例如 angularvueember 等。

自定义服务设置

为了演示如何从资源中提供单页应用程序服务,让我们假设我们的应用程序位于 sample-web-app 资源包中,其结构如下:

text
sample-web-app
├── main.html
├── ktor_logo.png
├── css
│   └──styles.css
└── js
    └── script.js

要提供此应用程序,可以使用以下配置:

kotlin
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.routing.*

fun Application.module() {
    routing {
        singlePageApplication {
            useResources = true
            filesPath = "sample-web-app"
            defaultPage = "main.html"
            ignoreFiles { it.endsWith(".txt") }
        }
    }
}
  • useResources:启用从资源包提供应用程序服务的功能。
  • filesPath:指定应用程序所在的路径。
  • defaultPage:将 main.html 指定为要提供的默认资源。
  • ignoreFiles:忽略以 .txt 结尾的路径。

您可以在此处找到完整的示例:single-page-application