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

问题描述 投票:0回答:1

这是我直接从Spark documentation拍摄的CorsRoute:

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响应?

java kotlin spark-java
1个回答
2
投票

因为

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

是一个lambda,它返回一个没有参数的lambda,而不是一个String。内在的lambda的toString返回() -> kotlin.String

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

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

(有关格式约定,请参阅https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-formatting

© www.soinside.com 2019 - 2024. All rights reserved.