求助play 设置 跨域

分享 未结
0 0 2 8
v-java 2019-02-26发布
收藏 点赞

q前后端分离开发 遇到跨域问题;

回帖
  • 2019-02-27

    第1步:抽象一个CORSAction,为结果添加响应头:

    object CORSAction extends ActionBuilder[Request] {
      def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
        block(request).map{ result =>
          result.withHeaders(
            "Access-Control-Allow-Origin" -> "*",
            "Access-Control-Allow-Headers" -> "Content-Type, Content-Length, Authorization, Accept, X-Requested-With",
            "Access-Control-Allow-Methods" -> "PUT, POST, GET, DELETE, OPTIONS"
          )
        }
      }
    }
    

    第2步:在RequestHandler中处理OPTIONS请求:

    if (request.method.toUpperCase == "OPTIONS"){
      Some(Action(
        Results.Ok("").withHeaders(
        "Access-Control-Allow-Origin" -> "*",
        "Access-Control-Allow-Headers" -> "Content-Type, Content-Length, Authorization, Accept, X-Requested-With",
        "Access-Control-Allow-Methods" -> "PUT, POST, GET, DELETE, OPTIONS"
      )))
    }
    


    1 回复
  • 2019-03-18

    我觉得没那么麻烦,配置下过滤器就可以了,加上如下配置

    play.filters.headers {
      frameOptions = null
      xssProtection = null
      contentTypeOptions = null
      permittedCrossDomainPolicies = null
      contentSecurityPolicy = null
      referrerPolicy = null
      allowActionSpecificHeaders = false
    }
    


    0 回复