【发布时间】: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)
那么如何让这些请求生效呢?
【问题讨论】: