喷雾跨域无法正常工作

时间:2020-08-20 19:45:08

标签: scala cors spray

我正在尝试从一台服务器到另一台服务器进行跨域api调用。对于此OPTIONS请求,该请求已成功完成,但实际请求(GET,POST,PUT,DELETE)失败,并且CORS缺少允许来源

以下是我要添加的代码

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的所有路由(因此请求变为api / something)

并以In request Status it has 404 Not Found

的形式获取错误

那么如何使这些请求起作用?

1 个答案:

答案 0 :(得分:0)

当我的客户代码发送对GET http://localhost:8080//menu的请求时,我遇到了相同的错误,因此在端口号后加了一个/。从客户端调用中删除多余的/可以解决此问题。