ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
13k stars 1.06k forks source link

"TypeError: this.local$body.on is not a function" on ktor-client-js with node-fetch environment #1674

Closed subroh0508 closed 4 years ago

subroh0508 commented 4 years ago

Ktor Version and Engine Used (client or server and name) Version: 1.3.1 Engine: Js-Client

Describe the bug The module specifying js { nodejs() } and building called from JavaScript, throws "TypeError".

For example, the code blow.

private const val HOSTNAME = "sparql.crssnky.xyz"
private const val ENDPOINT = "/spql/imas/query"

val client = HttpClient(Js) {
    defaultRequest {
        accept(ContentType("application", "sparql-results+json"))
    }
    install(JsonFeature) {
        serializer = KotlinxSerializer(Json.nonstrict)
        acceptContentTypes += ContentType("application", "sparql-results+json")
    }
}

// -> Throws "TypeError: this.local$body.on is not a function"! 
val response = httpClient.get<Response>(buildQuery()) {
    url {
        protocol = URLProtocol.HTTPS
        host = HOSTNAME
    }
}

private fun buildQuery(): String = buildString {
    append(ENDPOINT)
    append("?output=json")
    append("&query=")

    val query = """
        some queries...
    """.trimIndent()

    append(URLEncoder.encode(query))
}

@Serializable
data class Response(...)

Repository URL: https://github.com/subroh0508/ktor-client-mpp-sample/tree/by-node-fetch

Expected behavior Does not throw any errors on node-fetch environment.

Screenshots

MacScreenShot 2020-02-24 23 13 39
e5l commented 4 years ago

Hi @subroh0508, node-fetch package is used for node-js modules only. It looks like it selected wrong runtime. I'll take a look on the reproducer first.

subroh0508 commented 4 years ago

@e5l Thank you for your reply!

node-fetch package is used for node-js modules only

As you say, the case specifying js { browser() } and written entirely in Kotlin was selected window.fetch. Like blow(and this code can receive response correctly).

https://github.com/subroh0508/ktor-client-mpp-sample/blob/master/web/src/main/kotlin/main.kt#L23

But, the case transpiling JS and using from JS code was selected node-fetch. Like below(and this code always throws TypeError, so I want to fix it).

https://github.com/subroh0508/ktor-client-mpp-sample/blob/53fc625b4d6504ce52eec3e624707873b4bf5c1a/desktop/renderer/index.js#L1

I'd like to check, should PlatformUtil.IS_NODE be false when importing transpiled Kotlin/JS modules from build/js/packages/* directory and using them in JS code?

subroh0508 commented 4 years ago

Fixed my code 💪