Play 2.0.1 and setting Access-Control-Allow-Origin(播放 2.0.1 并设置 Access-Control-Allow-Origin)
问题描述
我有一个 Play 2.0.1 应用程序,我想使用托管在其他域上的 Javascript 来调用它.我的 Javascript 调用失败:
I have a Play 2.0.1 application that I want to call using Javascript hosted on other domains. My Javascript call is failing with:
Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.
我找到了一些关于如何在 Play 1 中设置正确 HTTP 标头的示例,但没有找到适用于 Play 2.0.1 的任何内容.阅读文档 (http://www.playframework.org/documentation/2.0.2/JavaResponse) 后,我尝试了以下操作以使事情正常进行:
I have found a number of examples of how to set the correct HTTP header in Play 1, but have not found anything for Play 2.0.1. After reading the documentation (http://www.playframework.org/documentation/2.0.2/JavaResponse) I've tried the following just to get things working:
public static Result myJsonWebService() {
...
response().setHeader("Access-Control-Allow-Origin", "*");
return ok(toJson(jsonObject));
}
但我的 JS Web 服务调用仍然失败.
but my JS web service call is still failing.
我需要做什么才能让它工作?
What do I need to do to get this working?
推荐答案
对于 Scala 的人来说,这是我目前正在使用的实现:
Just for Scala guys, this is the implementation I'm currently using:
import play.api.mvc._
import scala.concurrent._
import play.api.http.HeaderNames._
/**
* Action decorator that provide CORS support
*
* @author Giovanni Costagliola, Nick McCready
*/
case class WithCors(httpVerbs: String*)(action: EssentialAction) extends EssentialAction with Results {
def apply(request: RequestHeader) = {
implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext
val origin = request.headers.get(ORIGIN).getOrElse("*")
if (request.method == "OPTIONS") { // preflight
val corsAction = Action {
request =>
Ok("").withHeaders(
ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
ACCESS_CONTROL_ALLOW_METHODS -> (httpVerbs.toSet + "OPTIONS").mkString(", "),
ACCESS_CONTROL_MAX_AGE -> "3600",
ACCESS_CONTROL_ALLOW_HEADERS -> s"$ORIGIN, X-Requested-With, $CONTENT_TYPE, $ACCEPT, $AUTHORIZATION, X-Auth-Token",
ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true")
}
corsAction(request)
} else { // actual request
action(request).map(res => res.withHeaders(
ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
))
}
}
}
要使用它,只需按以下方式装饰您的操作:
To use it just decorate your action in the following way:
def myAction = WithCors("GET", "POST") {
Action { request =>
???
}
}
这篇关于播放 2.0.1 并设置 Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:播放 2.0.1 并设置 Access-Control-Allow-Origin
基础教程推荐
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01