Play 框架 CORS 标头 [英] Play Framework CORS Headers

查看:27
本文介绍了Play 框架 CORS 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的播放框架应用设置 CORS 标头.具体来说,我收到此错误

I'm trying to set CORS Headers for my play framework app. Specifically I'm getting this error

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.

我想我可以按照以下说明轻松处理此问题:https://www.playframework.com/documentation/2.5.x/CorsFilter

I figured I could easily handle this by following these instructions: https://www.playframework.com/documentation/2.5.x/CorsFilter

然而,在这样做之后.什么也没有变.

However, after doing this. nothing has changed.

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

我的配置是:

play.http.filters = "global.Filters"

play.filters.cors {
  allowedOrigins = ["http://www.example.com", "*"]
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
}

我的 Filters.scala 文件是:

and my Filters.scala file is:

package global

import javax.inject.Inject
import play.api.http.DefaultHttpFilters
import play.filters.cors.CORSFilter

class Filters @Inject() (corsFilter: CORSFilter)
  extends DefaultHttpFilters(corsFilter)

如果有人能告诉我为什么过滤器似乎没有应用于响应,那就太好了.

If someone could tell me why the filters don't seem to be getting applied to the responses, that'd be great.

推荐答案

播放过滤器很诱人,但当它们没有按预期工作时,正如您所注意到的,魔法并不是那么容易追踪.

Play filters are enticing, but when they do not work as expected, as you noticed, the magic is not that easy to track down.

我更喜欢使用这样的东西:

I prefer to use something like this:

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"
  )
}

然后您可以像这样轻松地在响应中调用它:

Then you can easily invoke it in your response like this:

Ok(Json.obj("ok" -> "1")).enableCors

简单易懂,可以放在需要开启CORS的地方,而且很容易调试!

It's easy to understand, can be placed only where you want to enable CORS, and very easy to debug!

这篇关于Play 框架 CORS 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆