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