【发布时间】:2019-06-17 01:04:45
【问题描述】:
我正在使用 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);
})
请帮帮我
【问题讨论】:
-
如果您收到前面提到的 403,则意味着您的 OPTIONS 请求因没有足够的权限而被拒绝。这很可能就是为什么标题丢失的原因。首先尝试调查权限错误。顺便说一句,您声明的错误消息与您的代码不匹配 - 网址不同
-
我在localhost上测试过,但错误是一样的
-
好吧,这很好解释,但它没有解释 403。您需要更深入地研究您的设置,看看为什么对该 URL 的调用返回 Forbidden。如果您尝试直接在浏览器窗口中访问相同的结果(即通过将其粘贴到地址栏中,而不是使用 fetch()),它是否也会返回 403 Forbidden?我意识到这不会生成 OPTIONS 请求,但它至少可以向我们展示它是否可以通过常规 GET 访问。如果问题仅针对 OPTIONS 请求,或者是整个 URL 的问题,我们可以缩小范围。
-
常规获取请求适用于浏览器
标签: javascript kotlin ktor