I am trying to do cross-domain api calling from one server to another. For this OPTIONS request is completing successfully but actual requests(GET, POST, PUT, DELETE) are failing with CORS Missing Allow Origin
Following is the code I'm adding
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)
I'm using it this corsHandler directive as :
lazy val apiRoutes: Route = corsHandler({
pathPrefix("api") {
jsonRoutes ~
reject(UnmatchedPathRejection())
}
})
Note: jsonRoutes contains all routes of GET, POST, PUT, DELETE(so request becomes api/something)
So how to make these requests work?

I got the same error when my client code sent a request for
GET http://localhost:8080//menu, so with a double/after the port number. Removing the extra / from the client call fixed the problem.