【发布时间】:2016-12-14 05:29:42
【问题描述】:
我正在尝试在使用 akka-http-cors 时为我的 akka http API 添加 CORS 支持:https://github.com/lomigmegard/akka-http-cors
当我基本上将 cors 支持添加到 simple 路线时,一切正常,例如:
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 的不同实现(基于自定义特征),并且它们的行为都是相同的。
我在这里错过了什么?
【问题讨论】: