【问题标题】:Play framework AngularJs CORS post json播放框架AngularJs CORS post json
【发布时间】:2014-03-24 09:55:50
【问题描述】:

我有一个 AngularJs 前端和一个 playframework 2 Scala 后端。查看 this 将 COR 添加到后端 - 我有两个端点:GET 和 POST

GET         /api/question/:id              controllers.Questions.getQuestion(id: String)
POST        /api/question/:id              controllers.Questions.postQuestion(id: String)

其他响应中提供的此解决方案适用于 GET,但不适用于 POST

def getQuestion(key:String) = CorsAction{
    ....

  }




def postQuestion(key:String) = CorsAction(parse.json){
               req =>
      ........
  }

我的理解是CORsAction(扩展ActionBuilder)也可以接受bodyparser的方法,因此基本上也应该适用于POST请求。

这是我从前端点击 POST 时在浏览器控制台中看到的内容。

OPTIONS http://localhost:9000/api/question/abc123 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. angular.js:7997
XMLHttpRequest cannot load http://localhost:9000/api/question/abc123. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. 

【问题讨论】:

    标签: json scala post playframework-2.0 cors


    【解决方案1】:

    所以我不确定确切的问题,但将以下内容添加到路线中 解决了问题

    OPTIONS        /api/question/:id             controllers.Application.preflight(id)
    

    预检端仅返回带有 COR 标头的 Ok。但我会认为 CorsAction 应该处理这个问题。无论如何,继续前进。

    【讨论】:

    • 如何返回 CORS 标头?使用Ok().withHeaders(...)?
    • 对于您的每个Ok(...),您是否添加了withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")?我能够通过将 withHeaders 附加到我的每个 HTTP 响应标头来解决我的 CORS 问题 - 不仅是飞行前响应的标头。
    • 我只需要将它添加到我的 OPTIONS 请求中。如果这就是您的意思,则不适用于 GET / POST。
    • 嗯,只有 withHeaders(...) 添加到我的 GET / POST 请求后,CORS 才对我有用。
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2012-06-02
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多