【问题标题】:spray cross-domain is not working cors scala跨域喷雾不起作用 cors scala
【发布时间】:2020-08-20 19:45:08
【问题描述】:

我正在尝试从一台服务器到另一台服务器进行跨域 api 调用。对于此 OPTIONS 请求已成功完成,但实际请求(GET、POST、PUT、DELETE)因 CORS Missing Allow Origin 而失败

以下是我要添加的代码

private val corsResponseHeaders = List(
  `Access-Control-Allow-Origin`(AllOrigins),
  `Access-Control-Allow-Credentials`(true),
  `Access-Control-Allow-Headers`("Authorization", "Content-Type", "Csrf-Token"),
  `Access-Control-Max-Age`(1728000)//Tell browser to cache OPTIONS requests
)
//this directive adds access control headers to normal responses
private def addAccessControlHeaders: Directive0 = {
  respondWithHeaders(corsResponseHeaders)
}
//this handles preflight OPTIONS requests.
private def preflightRequestHandler: Route = options {
  println("allowed-method==================================")
  complete(HttpResponse(StatusCodes.OK).
    withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
}
// Wrap the Route with this method to enable adding of CORS headers
def corsHandler(r: Route): Route = addAccessControlHeaders {
  println("cors-handler==================================")
  preflightRequestHandler ~ r
}
// Helper method to add CORS headers to HttpResponse
// preventing duplication of CORS headers across code
def addCORSHeaders(response: HttpResponse):HttpResponse =
  response.withHeaders(corsResponseHeaders)

我将这个 corsHandler 指令用作:

lazy val apiRoutes: Route = corsHandler({
    pathPrefix("api") {
      jsonRoutes ~
      reject(UnmatchedPathRejection())
    }
  })

注意:jsonRoutes包含了GET、POST、PUT、DELETE的所有路由(所以request变成了api/something)

得到错误

那么如何让这些请求生效呢?

【问题讨论】:

    标签: scala cors spray


    【解决方案1】:

    当我的客户端代码发送GET http://localhost:8080//menu 的请求时,我遇到了同样的错误,所以在端口号后面加上了双/。从客户端调用中删除额外的 / 解决了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多