Hi, guys! Recently started to develop full stack a...
# ktor
v
Hi, guys! Recently started to develop full stack application using kotlin with ktor as backend. And now i have a problem with cors policy
Copy code
Access to fetch at '<http://127.0.0.1:8080/api/run?userId=root&profile=test>' from origin '<http://localhost:3000>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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
As i understand, i should add origin to list of allowed origins in my backend app, i do this that way
Copy code
install(CORS){
        method(HttpMethod.Get)
        method(<http://HttpMethod.Post|HttpMethod.Post>, )
        method(HttpMethod.Delete)
        anyHost()
        host("localhost")
    }
But this dont work. This is headers of response from js clinet
Copy code
'Origin': '<http://localhost:3000>',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Access-Control-Request-Headers': 'Content-Type, Authorization'
Can anyone help me please?
j
Hello @Vasily Scherbakov, I had this problem recently and solved it this way
Copy code
install(CORS) {
    method(HttpMethod.Options)
    method(<http://HttpMethod.Post|HttpMethod.Post>)
    method(HttpMethod.Get)
    method(HttpMethod.Put)
    method(HttpMethod.Delete)
    method(HttpMethod.Head)
    header(HttpHeaders.AccessControlAllowHeaders)
    header(HttpHeaders.ContentType)
    header(HttpHeaders.AccessControlAllowOrigin)
    header(HttpHeaders.AccessControlAllowMethods)
    header("userToken")
    allowCredentials = true
    allowNonSimpleContentTypes = true
    hosts.addAll(initHostsOrigins())
}
I created a private function
initHostsOrigins
, where I get the hosts from my
application.conf
file
Copy code
private fun initHostsOrigins() = ConfigFactory.load().getString("cors.allowed-origins")
    .split(",")
    .stream()
    .map { it.trim() }
    .filter { it.isNotBlank() }
    .collect(Collectors.toList())
The variable in my
application.conf
file looks like this
Copy code
cors: {
  allowed-origins: "<http://localhost:3000>,<http://localhost:8080>"
}
I hope I can help you in some way
Were you able to solve? @Vasily Scherbakov
v
Oh, sorry for missing response! Yes, thats help me. Even without allowed hosts specifying. Looks like problem was in missing headers specifying
Thanks 👍
j
Thanks