I have a demo project where I'm testing various architectural approaches, patterns, and technologies for Android. Currently, I am working on the server side using Kotlin Multiplatform and have encountered a technical issue that I cannot resolve myself. Here's the task: I have a Ktor server that returns a list of objects upon request:
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
routing {
get("/repos/octocat/Spoon-Knife/forks") {
call.respondText(forksJson(), ContentType.Application.Json, HttpStatusCode.OK)
}
}
}
And a client - a website that also uses Ktor to send requests to the server to retrieve a list of objects:
HttpClient {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
}
I run the server and the web application on the same laptop (macOS). When trying to execute the request, I receive the following error:
Access to fetch at 'http://localhost:8080/repos/octocat/Spoon-Knife/forks' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried different solutions, such as setting up CORS on the server:
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Get)
allowMethod(HttpMethod.Post)
allowHeader(HttpHeaders.XForwardedProto)
allowHeader(HttpHeaders.Authorization)
allowHeader(HttpHeaders.ContentType)
allowCredentials = true
anyHost()
}
And settings on the client side:
httpClient.get("${baseUrl}repos/octocat/Spoon-Knife/forks") {
headers.append("Access-Control-Allow-Origin", "http://localhost:8080")
headers.append("Access-Control-Allow-Credentials", "true")
}
Unfortunately, nothing has worked to achieve the desired result. I would be grateful for any help.
While setting up CORS in the server you have forgot to add one header, which is causing you the issue.If you add the header for access control allow origin, it should work fine. You can add it like this:
allowHeader(HttpHeaders.AccessControlAllowOrigin)