Play! 2.0 easy fix to OPTIONS response for router catch-all?

六月ゝ 毕业季﹏ 提交于 2019-12-14 02:57:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!