[英]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")
}
header
和exposeHeader
之間的區別 - 首先允許使用此標頭進行調用,但其次允許在客戶端使用它
確保在 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.