Additional `options` directive required for CORS to work
ksilin opened this issue · 3 comments
I have a route for POST
requests which should accept frontend requests
Expected behaviour: cors(settings){ route }
should be enough to serve CORS requests
Actual behaviour: 405, Method not allowed
is returned on the OPTIONS
request
Workaround: add a simple options
directive to route
private val methods = List(GET, PUT, POST, PATCH, HEAD, DELETE, OPTIONS)
val corsSettings: CorsSettings.Default =
CorsSettings.defaultSettings.copy(allowedMethods = methods)
val fullRoute = handleRejections(CorsDirectives.corsRejectionHandler) {
cors(corsSettings) {
handleRejections(RejectionHandler.default) {
path("upload") {
// options {
// complete(HttpResponse(StatusCodes.OK).withHeaders(`Access-Control-Allow-Methods`(methods: _*)))
// } ~
post {
fileUpload("img") {
case (fileInfo: FileInfo, fileStream: Source[ByteString, Any]) =>
logger.info(s"storing ${fileInfo.contentType} / ${fileInfo.fieldName} / ${fileInfo.fileName}")
complete(StatusCodes.OK)
}
}
}
}
}
}
Hi,
Can you provide the cURL commands you are using to test this route, or at least the complete response that you get back?
It seems the preflight request (required before a POST method) is not interpreted as such. Perhaps a missing Origin
or Access-Control-Request-Method
header? Both are required to be a valid preflight request.
If you disable the allowGenericHttpRequests
setting, you will quickly see if the CORS request is valid.
@lomigmegard Sorry, the JS code in my form was incorrect. Your code works perfectly without any additional directives.
Thank you for the help and please excuse the inconvenience :)
@ksilin no worries :)