javascript - ktor cors header 中的 Access-Control-Allow-Origin 问题

标签 javascript kotlin ktor

我正在使用 ktor 和 cors 构建一个简单的 REST API,但是当我发送一个没有 header 数据的简单 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.

这是我的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))
        }

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

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

请帮帮我

最佳答案

您需要像这样将 header 列入白名单:

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

这需要对您打算使用的每个自定义 HTTP header 完成。

关于javascript - ktor cors header 中的 Access-Control-Allow-Origin 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327270/

相关文章:

javascript - 获取所有已声明模块导入的列表 (SystemJS)

javascript - 如何在没有重定向页面的情况下使用 jquery post 发送大数据?

javascript - 将水平图像放入 HTML 脚本中

android - 导航到另一个 Fragment 时,Fragment 中的 RecyclerView 崩溃

android - ktor 依赖关系未在多平台项目的 ios 模块中解析

android - KMM : How to resolve Incompatible abi version. 当前默认为 '1.4.2' ,找到 '1.5.0' 。 1.5.20编译器产生的库?

javascript - 使用 Node JS 访问 API 并将其解析为 JSON 文件

android - NoWhenBranchMatchedException 在 Kotlin 中具有详尽的 `when` block

generics - 用于通用列表的 Moshi 自定义适配器 <T :Enum> returns List<List<T:Enum>> instead of List<T:Enum>

http - 在 Ktor 中测试 Post 请求