Skip to content
Advertisement

Access-Control-Allow-Origin issue in ktor cors header

I am building a simple REST API using ktor and used cors but when i send a simple get request with no headers data the server works fine but if i want the client to have say key:1 the server doesn`t respond me correctly, it says the problem is

Failed to load http://127.0.0.1:8080/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

so here is my ktor code

install(ContentNegotiation) {
        gson {
        }
    }
    install(ForwardedHeaderSupport)
    install(DefaultHeaders)
    install(CORS)
    {
        method(HttpMethod.Options)
        method(HttpMethod.Get)
        method(HttpMethod.Post)
        method(HttpMethod.Put)
        method(HttpMethod.Delete)
        method(HttpMethod.Patch)
        header(HttpHeaders.AccessControlAllowHeaders)
        header(HttpHeaders.ContentType)
        header(HttpHeaders.AccessControlAllowOrigin)
        allowCredentials = true
        anyHost()
        maxAge = Duration.ofDays(1)
    }
...
 get("test"){
            val a =  call.request.headers["key"]
            println(a)
            call.respond(Product(name = a))
        }

and my javascript code looks like this….

fetch('http://shop-ix.uz:8080/test', {
 headers: {
 "key": "1" 
})
   .then(response => response.json())
   .then(json => {    
     console.log(json);
   })

please help me

Advertisement

Answer

You need to whitelist your headers like this:

install(CORS) {
  header("key")
}

This needs to be done with every custom HTTP header you intend to use.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement