在使用akka-http-cors
:https://github.com/lomigmegard/akka-http-cors时,我试图为我的akka添加CORS支持
例如,当我将cors支持添加到一个简单的路由时,一切都很好:
val route = cors() {
path("ping") {
get {
complete("pong")
}
}
}
使用相应的jQuery调用:
$.ajax({
url: "http://localhost:9000/ping",
type: "GET",
success: function(data) { alert(data); }
});
按预期正确返回"pong"
但是当我试图从请求中提取(服务器端)某些特定的头时,cors对响应的支持似乎突然中断了。例如,有:
val route = cors() {
headerValueByName("myheader") { (myheader) =>
path("ping") {
get {
complete("pong")
}
}
}
}
使用相应的jQuery调用:
$.ajax({
url: "http://localhost:9000/ping",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('myheader', 'test');},
success: function(data) { alert('Success!' + data); }
});
在控制台中出现cors错误时失败:
XMLHttpRequest cannot load http://localhost:9000/ping.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
The response had HTTP status code 400.
在路由中添加headerValueByName(...)似乎破坏了cors的支持,我不知道为什么。
我也尝试过不同的cors实现(基于自定义特性),它们的行为都是相同的。
我在这里错过了什么?
发布于 2016-12-13 21:29:42
请使用像curl
这样的工具调试服务器路由,以查看来自服务器的实际响应,而不是JavaScript的解释。
curl -X GET -H "Origin: http://example.com" -H "myheader: test" http://localhost:9000/ping
我怀疑您的自定义头没有在HTTP请求中正确地发送。然后,headerValueByName
指令将拒绝请求。拒绝弹出(跳过cors
指令),最终由默认的拒绝处理程序处理。因此,与CORS相关的标头没有响应。
您应该将您的拒绝和异常处理程序放在-- cors
指令中,而不是在外部(与默认的指令一样)。请看下面的例子。
def route: Route = {
import CorsDirectives._
import Directives._
// Your CORS settings
val corsSettings = CorsSettings.defaultSettings
// Your rejection handler
val rejectionHandler = corsRejectionHandler withFallback RejectionHandler.default
// Your exception handler
val exceptionHandler = ExceptionHandler {
...
}
// Combining the two handlers only for convenience
val handleErrors = handleRejections(rejectionHandler) & handleExceptions(exceptionHandler)
// Note how rejections and exceptions are handled *before* the CORS directive (in the inner route).
// This is required to have the correct CORS headers in the response even when an error occurs.
handleErrors {
cors(corsSettings) {
handleErrors {
... // your business route here
}
}
}
}
这不会解决您的头问题,但是即使路由被拒绝或异常失败,CORS头至少也将是HTTP响应的一部分。
https://stackoverflow.com/questions/40723715
复制相似问题