0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ktor】CORSの設定をしてみた

0
Posted at

概要

今回はKtorでCORSの設定をしてみましたので、メモ書きとして残しておきます。なお、KtorでのCORSの設定についてはこちらのドキュメントに、設定の概要などが記載されています。

設定項目

取り急ぎ、APIサーバにおいて最低限必要と思われる、以下の項目を今回設定してみました。

  • method:GetPostPutDeleteOptionsを設定します。
  • host:APIのリクエストを行うフロントエンドのURLを設定します。なお、今回はURLのauthorityschemaを設定してみました。
  • allowCredentials:trueを設定します。
  • allowNonSimpleContentTypes:この項目はKtor独自の項目のようで、json形式のリクエストを受け取りたい場合はtrueを設定します。こちらに記載されている、simple content type以外のリクエストを受け取りたい場合、trueを設定する必要があるようです。

実装サンプル

フロントエンドのURLをapplication.confに定義します。

application.conf
serverInfo {
    frontendUrl = "http://localhost:3000"
}

KtorのApplication.moduleにCORSの設定を行います。

Application.kt
fun Application.module() {
    val frontEndUri = URI(environment.config.property("serverInfo.frontendUrl").getString())
    install(CORS) {
        method(HttpMethod.Get)
        method(HttpMethod.Post)
        method(HttpMethod.Put)
        method(HttpMethod.Delete)
        method(HttpMethod.Options)
        host(frontEndUri.authority, schemes = listOf(frontEndUri.scheme))
        allowCredentials = true
        allowNonSimpleContentTypes = true
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?