Skip to content

Instantly share code, notes, and snippets.

@kmikulski
Created December 5, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmikulski/f2a294c9df3eb733f2b75bf83ec22d0d to your computer and use it in GitHub Desktop.
Save kmikulski/f2a294c9df3eb733f2b75bf83ec22d0d to your computer and use it in GitHub Desktop.
the description for this gist
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.{ HttpResponse, StatusCodes }
import akka.http.scaladsl.server.Directives.{ complete, options, respondWithHeaders, _ }
import akka.http.scaladsl.server.{ Directive0, Route }
trait CORSHandler {
private val corsResponseHeaders = List(
`Access-Control-Allow-Origin`.*,
`Access-Control-Allow-Credentials`(true),
`Access-Control-Allow-Headers`("Authorization", "Content-Type", "X-Requested-With"))
private def addAccessControlHeaders: Directive0 = {
respondWithHeaders(corsResponseHeaders)
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(StatusCodes.OK).
withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
}
def corsHandler(r: Route): Route = addAccessControlHeaders {
preflightRequestHandler ~ r
}
def addCORSHeaders(response: HttpResponse): HttpResponse =
response.withHeaders(corsResponseHeaders)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment