繁体   English   中英

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

[英]Access-Control-Allow-Origin issue in ktor cors header

我正在使用 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.

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

请帮我

您需要像这样将您的标头列入白名单:

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

这需要对您打算使用的每个自定义 HTTP 标头进行。

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

headerexposeHeader之间的区别 - 首先允许使用此标头进行调用,但其次允许在客户端使用它

确保在 Ktor CORS 安装期间应允许所有标头和所需方法。 我遇到了同样的问题,然后我意识到我没有添加allowHeader(HttpHeaders.AccessControlAllowOrigin)尽管在请求标头中它存在。 因此,我遇到了禁止错误(403)!

我的请求标头!

Axios({
        method: 'GET',
        url: 'http://127.0.0.1:8080/connect',
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json",
        },
        params: {
          ...
        }
})

允许 CORS

    install(CORS) {
        allowMethod(HttpMethod.Options)
        allowMethod(HttpMethod.Post)
        allowMethod(HttpMethod.Get)
        allowHeader(HttpHeaders.AccessControlAllowOrigin)
        allowHeader(HttpHeaders.ContentType)
        anyHost()
    }

在 CORS 期间检查服务器上是否允许您的请求标头所需的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM