Play框架的CORS请求

5

我有两个应用程序:

  1. 在localhost:9000上运行的Play 2.6.7应用程序
  2. 运行在localhost:3000上的webpack开发服务器

Webpack应用程序向Play应用程序发出POST请求。

$.ajax({
  url: 'http://localhost:9000/users',
  data: JSON.stringify(data),
  dataType: 'json',
  method: 'POST'
})

Play应用程序会做出响应。
Failed to load http://localhost:9000/users: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

只有在Play应用程序中使用以下语句明确设置标头时,才会发送请求标头:

def create = Action { 
  Ok("stuff").withHeaders(
    "Access-Control-Allow-Origin" -> "http://localhost:3000"
  )
}

请求是否无误发送。

我的问题是:为什么Play框架不像文档中所说的那样自动设置这个头呢?我的application.conf是一个空文件。

1个回答

8
CORS过滤器默认情况下未启用。添加:
play.filters.enabled += play.filters.cors.CORSFilter

将配置文件 application.conf 解决此问题


这里有一个可用的示例。https://github.com/techmonad/play-cors-example - Sky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接