Put Error
Ciaran0 opened this issue · 7 comments
How can I allow my application perform put's
java.lang.RuntimeException: Unhandled rejection: CorsRejection(None,Some(HttpMethod(PUT)),None)
Thanks
Hi,
You have to change the default value of the allowedMethods
setting to include the PUT
method. For example:
import akka.http.scaladsl.model.HttpMethods._
import scala.collection.immutable
val settings = CorsSettings.defaultSettings.copy(allowedMethods = immutable.Seq(
GET, PUT, POST, HEAD, OPTIONS
))
val route: Route = cors(settings) {
...
}
Also you should use the rejection handler to have better error messages (or modify it to your needs):
import akka.http.scaladsl.server.directives.ExecutionDirectives._
import ch.megard.akka.http.cors.CorsDirectives._
val route: Route = handleRejections(corsRejectionHandler) {
cors(settings) {
...
}
}
Let me know if it is still unclear.
That solved the problem, thanks!
It might be worthwhile putting this in the readme.
I'm using the java version of the cors library. How would one change the allowedMethods settings? The CorsSettings.defaultSettings() returns me an immutable object - how can I copy or create a mutable version in Java?
Thanks.
Hi @starlabs007,
Why do you need a mutable CorsSettings? Can you describe more in detail? It seems you could use API to create your own CorsSettings instead of defaultSettings.
There are the APIs you could work with.
def withAllowGenericHttpRequests(newValue: Boolean): CorsSettings
def withAllowCredentials(newValue: Boolean): CorsSettings
def withAllowedOrigins(newValue: HttpOriginRange): CorsSettings
def withAllowedHeaders(newValue: HttpHeaderRange): CorsSettings
def withAllowedMethods(newValue: java.lang.Iterable[HttpMethod]): CorsSettings
def withExposedHeaders(newValue: java.lang.Iterable[String]): CorsSettings
def withMaxAge(newValue: Optional[Long]): CorsSettings
@jiminhsieh Thank you that worked. I didn't know those functions returned a customized cors settings object.
For those using Java, this was the code to get a customized cors settings:
List<HttpMethod> allowedMethods = Arrays.asList(
HttpMethods.GET,
HttpMethods.POST,
HttpMethods.DELETE,
HttpMethods.PUT,
HttpMethods.OPTIONS,
HttpMethods.HEAD);
CorsSettings settings = CorsSettings.defaultSettings().withAllowedMethods(allowedMethods);
@starlabs007 Correct, the settings are still immutable, instead of using the copy
method from Scala, you have the with*
methods for the Java API.
For anyone using Scala coming here. Seems like the first answer where this is mentioned is not accurate anymore.
val settings = CorsSettings.defaultSettings.copy(allowedMethods = immutable.Seq(
GET, PUT, POST, HEAD, OPTIONS
))
Instead use this syntax
val settings: CorsSettings = CorsSettings
.defaultSettings
.withAllowedMethods(immutable.Seq(GET, PUT, POST, HEAD, OPTIONS, DELETE))