3
votes

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

2
if you're getting a 403 as mentioned then it implies your OPTIONS request was rejected as not having adequate permissions. This might well be why the header is then missing. Try to investigate the permissions error first. By the way, your stated error message doesn't match your code - the URLs are differentADyson
I tested on localhost but the error is the sameIsoq Hakimov
ok well that explains that, but it doesn't explain the 403. You need to dig a bit deeper into your setup to see why a call to that URL returns Forbidden. Does it also return 403 Forbidden if you try to access the same result directly in your browser window (i.e. by pasting it into the address bar, not by using fetch())? I realise this will not generate an OPTIONS request, but it might at least show us if it's accessible via a regular GET. Then we can narrow down if the issue is specific to OPTIONS requests only, or a problem with the whole URL.ADyson
the regular get request works with the browserIsoq Hakimov

2 Answers

5
votes

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.

0
votes
install(CORS) {
   exposeHeader("key")
}

difference between header and exposeHeader - first allow to make call with this header, but second allow to use it on client side