Play Framework CORS Headers

后端 未结 3 1787
星月不相逢
星月不相逢 2021-01-02 17:18

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         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-02 17:41

    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!

提交回复
热议问题