问题
Having some annoying issues making AJAX calls simply because almost every browser these days is making an OPTIONS call to the server before the actual AJAX call.
Since I am using Play! 2.0, is there any easy way to make a wildcard response to any route using the OPTIONS method?
For instance, in my routes do something like:
OPTIONS /* controllers.Options.responseDef
Yes I am aware that the new Play! doesn't have a wildcard built-in, but there needs to be a solution for this since all browsers are increasingly calling OPTIONS before AJAX calls.
回答1:
Not quite a wildcard, but you can use a route
which spans several slash-segments:
OPTIONS /*wholepath controllers.Options.responseDef(wholepath)
OPTIONS / controllers.Options.responseDef
It should match all the requests:
OPTIONS /a
OPTIONS /a/b
OPTIONS /a/b/c
Note: that's from the top of my head, so maybe you'll need to polish it. I can't check it now by myself.
Check the section Dynamic parts spanning several / of the manual.
回答2:
A very clean way to have a single controller endpoint match all OPTIONS requests is to override the onRouteRequest
method of Play's Global object. The following version of onRouteRequest
will route all requests to a single endpoint named OptionsController.options
.
import play.api.mvc._
...
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
request.method match {
case "OPTIONS" => Some(OptionsController.options)
case _ => super.onRouteRequest(request)
}
}
来源:https://stackoverflow.com/questions/11256241/play-2-0-easy-fix-to-options-response-for-router-catch-all