Hi. I’m developing a kotlin js react app and want ...
# javascript
l
Hi. I’m developing a kotlin js react app and want to use ktor client to call me REST api. Unfortunately the calls fail in the browser, probably because of some CORS related reason but I can’t seem to find a way to fix it. When I use
window.fetch
with exactly the same url it does work. Anyone has any how to fix this?
window.fetch:
Copy code
suspend fun fetchRestaurants(): Array<Restaurant> =
    window.fetch("<http://localhost:8081/api/v1/restaurants>")
        .await()
        .json()
        .await()
        .unsafeCast<Array<Restaurant>>()
Screen Shot 2021-01-10 at 9.06.29.png
with ktor:
Copy code
val response = client.get<HttpResponse> {
	url(Url("<http://localhost:8081/api/v1/restaurants>"))
}
image.png
t
Which Ktor version do you use?
l
Copy code
1.4.3
t
CORS support added in 1.5.0
Screen Shot 2021-01-11 at 1.10.56 AM.png
h
@turansky the cors support is for the ktor server, not for the ktor js client running in a browser :)
👌 1
s
this can be intended by server, you need to ask api provider about your site being added to whitelist maybe they have some non-production api that is not restricted, so you can develop freely without restrictions
l
the server is also mine, created with ktor
it seems to be working now, I had to add the following to the server:
Copy code
install(CORS) {
    method(HttpMethod.Options)
    method(HttpMethod.Get)
    method(<http://HttpMethod.Post|HttpMethod.Post>)
    method(HttpMethod.Put)
    method(HttpMethod.Delete)
    method(HttpMethod.Patch)
    header(HttpHeaders.AccessControlAllowHeaders)
    header(HttpHeaders.Accept)
    header(HttpHeaders.AcceptLanguage)
    header(HttpHeaders.ContentType)
    header(HttpHeaders.AccessControlAllowOrigin)
    header(HttpHeaders.Authorization)
    allowCredentials = true
    anyHost()
    maxAgeInSeconds = Duration.ofDays(1).seconds
}
😀 1
s
I actually got the same problem today, it was ContentType header in my case (post request didn't work). So thanks 🙂