scala Play 框架 CORS 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38315501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:28:28  来源:igfitidea点击:

Play Framework CORS Headers

scalaplayframeworkcors

提问by Aric Hunter

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

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

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.

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

我想我可以按照以下说明轻松处理此问题: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

My conf is:

我的配置是:

play.http.filters = "global.Filters"

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

and my Filters.scala file is:

我的 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)

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

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

回答by B Faust

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

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

很容易理解,可以放在你想启用CORS的地方,而且很容易调试!

回答by cyril

for me it worked after one day (maybe cash or other things)

对我来说,它在一天后起作用(可能是现金或其他东西)

application.conf:

应用程序.conf:

play.http.filters = "filters.Filters"

play.filters.cors {
  # allow all paths
  pathPrefixes = ["/"]
 # allow all origins (You can specify if you want)
 allowedOrigins = null
 allowedHttpMethods = ["GET", "POST"]
 # allow all headers
 allowedHttpHeaders = null
}  

build.sbt :

构建.sbt:

val appDependencies = Seq(
filters,
....
)

in package filters.Filter :

在包 filters.Filter 中:

package filters;

import javax.inject.Inject;
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

public class Filters extends DefaultHttpFilters {

CORSFilter corsFilter;

@Inject
public Filters(CORSFilter corsFilter) {
    super(corsFilter);
    this.corsFilter = corsFilter;
   }

public EssentialFilter[] filters() {
    return new EssentialFilter[] { corsFilter.asJava() };
}
}

and in my ajax call:

在我的 ajax 调用中:

$.ajax({
    method:'GET',
    url: xxxxxxxx',
    dataType: 'json',
    headers: {'url': yyyyy,
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT',
    'Access-Control-Allow-Headers': 'Content-Type'
    },
    success: function(data) { 
....}); 

i have no more error, in prod and in local environment !! thank you all

在生产环境和本地环境中,我不再有错误了!!谢谢你们

回答by mana

I would not recommend writing/using any code to enable CORS which is basically a framework feature and only needs configuration.

我不建议编写/使用任何代码来启用 CORS,这基本上是一个框架功能,只需要配置。

The stuff you copied from the documentation is correct:

您从文档中复制的内容是正确的:

  • cors.confwhere you modify the play.filters.corssettings. But you seem to have misconfigured something, e.g. the allowedOrigin = *should be configured as nullin the config. (Have a look at the documentation pageand the linked reference.conf)
  • cors.conf在哪里修改play.filters.cors设置。但是您似乎配置错​​误,例如allowedOrigin = *应该按照配置null中的方式进行配置。(查看文档页面和链接的reference.conf

# The allowed origins. If null, all origins are allowed. play.filters.cors.allowedOrigins = null

# The allowed origins. If null, all origins are allowed. play.filters.cors.allowedOrigins = null

  • You have correctly enabled the CORSFilterin your Filters.scala
  • Now test your configuration with a correct cURL CORS request:
  • 你已经正确启用CORSFilter您的Filters.scala
  • 现在使用正确的 cURL CORS 请求测试您的配置:

curl -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/

curl -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/