从浏览器请求时,CORS响应标头在Spray中不起作用

时间:2014-04-30 19:46:46

标签: jquery scala cors spray http-options-method

我试图在Spray服务器上实现CORS支持(版本1.1-20131011,其中已经支持cors头)。

目前,服务器代码如下所示:

trait DefaultCORSDirectives { this: Directives =>
  def defaultCORSHeaders = respondWithHeaders(
      `Access-Control-Allow-Origin`(AllOrigins),
      `Access-Control-Allow-Methods`(HttpMethods.GET, HttpMethods.POST, HttpMethods.OPTIONS, HttpMethods.DELETE,
      HttpMethods.CONNECT, HttpMethods.DELETE, HttpMethods.HEAD, HttpMethods.PATCH, HttpMethods.PUT, HttpMethods.TRACE),
      `Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host," +
    " Referer, User-Agent, Overwrite, Destination, Depth, X-Token, X-File-Size, If-Modified-Since, X-File-Name, Cache-Control"),
      `Access-Control-Allow-Credentials`(true),
      `Access-Control-Max-Age`(3600)
    )
}

并像这样使用

  defaultCORSHeaders {
      options {
        complete {
          StatusCodes.OK
        }
      } ~
      post {
        path("path") {
          //response
      }
   }

使用curl时,POST和OPTIONS方法的响应都是预期的。但是,从浏览器,我得到Access不允许使用Access-Control-Allow-Origin(Chrome)或错误415不支持的媒体类型(Firefox),似乎甚至根本没有发送POST请求。

请求的jQuery代码如下:

$(document).ready(function () {
        $.post(url,
            {
               'params': "params",
            },
            function (data) {
                //handle response
            }
    );
});

我已经阅读了CORS规范和我能找到的所有资源,尝试了Access-Control-Allow-headers的任何可能组合(有和没有Access-Control-Allow-Credentials,Access-Control-Allow的不同内容) -Headers和Access-Control-Allow-Methods,Access-Control-Allow-Origin设置为*或单个Origin等。我还尝试从磁盘(Origin null),webserver(Origin localhost:8888)和远程服务器(Origin标准url)运行脚本,因为某些浏览器显然会阻止具有本地原点的请求,但总是会产生相同的否定结果。

非常感谢任何帮助如何使这项工作。

3 个答案:

答案 0 :(得分:3)

我没有使用指令,但我尝试了rawheader并且它有效。

代码如下:

 path("ping"){
   get{
     respondWithMediaType(`application/json`){
       respondWithHeader(RawHeader("Access-Control-Allow-Origin","*")){
         complete{
           jsonPrefix + """{"result": "PONG"}"""
         }
       }
     }
   }
 }

答案 1 :(得分:2)

如果您在API中拥有授权,则必须在Access-Control-Allow-Headers中包含授权标题。

从cUrl测试cors的唯一方法是使用Origin标头:curl cors

答案 2 :(得分:0)

声明新指令:

trait CORSSupport extends Directives {
   private val CORSHeaders = List(
     `Access-Control-Allow-Methods`(GET, POST, PUT, DELETE, OPTIONS),
     `Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
     `Access-Control-Allow-Credentials`(true)
   )

   def respondWithCORS(origin: String)(routes: => Route) = {
     val originHeader = `Access-Control-Allow-Origin`(SomeOrigins(Seq(HttpOrigin(origin))))
     respondWithHeaders(originHeader :: CORSHeaders) {
       routes ~ options { complete(StatusCodes.OK) }
     }
   }
 }

使用新指令:

trait Api extends Directives with RouteConcatenation with CORSSupport with ConfigHolder{
    this: CoreActors with Core => 

    val routes =
      respondWithCORS(config.getString("origin.domain")) {

        pathPrefix("api") { 
          new DemoRoute().route
        } 
      }

    val rootService = system.actorOf(ApiService.props(config.getString("hostname"), config.getInt("port"), routes))
  }

https://github.com/wesovilabs/spray-cors-demo/blob/master/README.md