在 Kotlin 中启用 CORS 时访问路由时 Spark 返回空响应

Spark is returning an empty response when visiting a route when enabling CORS in Kotlin

这是我的 CorsRoute 直接取自 Spark documentation:

class CorsRoute(origin: String, methods: String, headers: String) {
    init {
        options("/*") { request, response ->

            val accessControlRequestHeaders = request.headers("Access-Control-Request-Headers")
            if (accessControlRequestHeaders != null) {
                response.header("Access-Control-Allow-Headers", accessControlRequestHeaders)
            }

            val accessControlRequestMethod = request.headers("Access-Control-Request-Method")
            if (accessControlRequestMethod != null) {
                response.header("Access-Control-Allow-Methods", accessControlRequestMethod)
            }

            "OK"
        }

        before { request, response ->
            response.header("Access-Control-Allow-Origin", origin)
            response.header("Access-Control-Request-Method", methods)
            response.header("Access-Control-Allow-Headers", headers)
            response.type("application/json")
        }
    }
}

以下是我如何实例化 CorsRoute:

abstract class Route {
    init {
        CorsRoute("*","*","*")
    }
}

这是我开始路线的方式:

class RestApiRoutes : Route() {
    fun init() {
        get("/test") {
            req, res -> {
                val obj = JsonObject().addProperty("foo", "bar")
                Gson().toJson(obj).toString()
            }
        }
    }
}

当我前往 http://127.0.0.1:4567/test 时,我收到:

() -> kotlin.String

为什么页面返回这个而不是我预期的 JSON 响应?

因为

{
    req, res -> {
        val obj = JsonObject().addProperty("foo", "bar")
        Gson().toJson(obj).toString()
    }
}

是一个 lambda,returns 是一个没有参数的 lambda,而不是 String。那个内部 lambda 的 toString returns () -> kotlin.String.

删除内部 {} 以解决问题:

{ req, res ->
    val obj = JsonObject().addProperty("foo", "bar")
    Gson().toJson(obj).toString()
}

(请参阅 https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-formatting 了解格式约定)