ktor cors 标头中的 Access-Control-Allow-Origin 问题

Iso*_*mov 3 javascript kotlin ktor

我正在使用 ktor 和使用 cors 构建一个简单的 REST API,但是当我发送一个没有标头数据的简单 get 请求时,服务器工作正常,但是如果我希望客户端说 key:1,服务器没有正确响应我,它说问题是

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.
Run Code Online (Sandbox Code Playgroud)

所以这是我的 ktor 代码

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))
        }
Run Code Online (Sandbox Code Playgroud)

我的 javascript 代码看起来像这样....

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

请帮我

fun*_*ude 5

You need to whitelist your headers like this:

install(CORS) {
  header("key")
}
Run Code Online (Sandbox Code Playgroud)

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