Ari*_*ter 4 scala cors playframework
我正在尝试为我的play框架应用程序设置CORS Headers.具体来说,我收到了这个错误
cannot load http://127.0.0.1:9000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
我想我可以按照以下说明轻松处理:https: //www.playframework.com/documentation/2.5.x/CorsFilter
但是,这样做之后.什么也没有变.
curl -I localhost:9000/
HTTP/1.1 200 OK
Content-Length: 4540
Content-Type: text/html; charset=utf-8
Date: Mon, 11 Jul 2016 20:03:33 GMT
Run Code Online (Sandbox Code Playgroud)
我的担心是:
play.http.filters = "global.Filters"
play.filters.cors {
allowedOrigins = ["http://www.example.com", "*"]
allowedHttpMethods = ["GET", "POST"]
allowedHttpHeaders = ["Accept"]
}
Run Code Online (Sandbox Code Playgroud)
和我的Filters.scala文件是:
package global
import javax.inject.Inject
import play.api.http.DefaultHttpFilters
import play.filters.cors.CORSFilter
class Filters @Inject() (corsFilter: CORSFilter)
extends DefaultHttpFilters(corsFilter)
Run Code Online (Sandbox Code Playgroud)
如果有人能告诉我为什么过滤器似乎没有应用于响应,那就太好了.
小智 14
播放过滤器很诱人,但是当它们没有按预期工作时,正如您所注意到的那样,魔术并不容易追踪.
我更喜欢使用这样的东西:
implicit class RichResult (result: Result) {
def enableCors = result.withHeaders(
"Access-Control-Allow-Origin" -> "*"
, "Access-Control-Allow-Methods" -> "OPTIONS, GET, POST, PUT, DELETE, HEAD" // OPTIONS for pre-flight
, "Access-Control-Allow-Headers" -> "Accept, Content-Type, Origin, X-Json, X-Prototype-Version, X-Requested-With" //, "X-My-NonStd-Option"
, "Access-Control-Allow-Credentials" -> "true"
)
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在响应中轻松调用它,如下所示:
Ok(Json.obj("ok" -> "1")).enableCors
Run Code Online (Sandbox Code Playgroud)
它很容易理解,只能放在你想要启用CORS的地方,并且非常容易调试!
我不建议编写/使用任何代码来启用 CORS,这基本上是一个框架功能,只需要配置。
您从文档中复制的内容是正确的:
cors.conf在哪里修改play.filters.cors设置。但是您似乎配置错误,例如allowedOrigin = *应该按照配置null中的方式进行配置。(查看文档页面和链接的reference.conf)# The allowed origins. If null, all origins are allowed.
play.filters.cors.allowedOrigins = null
CORSFilter您的Filters.scalacurl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose \
http://localhost:9000/
| 归档时间: |
|
| 查看次数: |
8852 次 |
| 最近记录: |