【问题标题】:Enable CORS on Angular + Scala Play在 Angular + Scala Play 上启用 CORS
【发布时间】:2014-07-29 13:56:27
【问题描述】:

使用 AngularJS 1.2.16 和 Scala Play 2.2.0,我正在尝试启用 CORS。

这是我在前端的请求。基本上它是一个POST,它发送一个带有userNamepassword 字段的JSON。

Request URL:http://localhost:9000/login
Request Headers CAUTION: Provisional headers are shown.
Accept:application/json, text/plain, */*
Content-Type:application/json;charset=UTF-8
Origin:http://localhost:8000
Referer:http://localhost:8000/app.html
User-Agent:Mozilla/5.0 ...
Request Payloadview source
  {userName:foo, password:bar}

这是后端checkPreFlight 方法,用于允许我的POST 请求的标头。

  def checkPreFlight = Action {
    Ok("...").withHeaders(
      ACCESS_CONTROL_ALLOW_ORIGIN -> "*",
      ACCESS_CONTROL_ALLOW_METHODS -> "POST",
      ACCESS_CONTROL_MAX_AGE -> "300",
      ACCESS_CONTROL_ALLOW_HEADERS -> "Origin, X-Requested-With, Content-Type, Accept,
                                         Referer, User-Agent")
  }

routes:

POST    /login                      controllers.Home.login
OPTIONS /login                      controllers.Home.checkPreFlight

我的 Chrome 浏览器控制台显示:

XMLHttpRequest cannot load http://localhost:9000/login. No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:8000' is therefore 
not allowed access. 

请注意,最初的 OPTIONS 请求返回了 200,但是 POST 在“网络”选项卡中被取消。 Chrome(根据 post)可能出于安全目的禁用 CORS 请求?

当我在 Firefox 上尝试时,OPTIONSPOST 都成功了,并且每个都具有 200 状态。但是,Firefox 在控制台中仍然显示错误:

200 OK 12ms 

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote 
resource at http://localhost:9000/login. This can be fixed by moving the resource 
to the same domain or enabling CORS.

此外,我的承诺(将 POST 称为/login)被拒绝,即我在成功和失败案例中添加了console.log

【问题讨论】:

  • 不能代表服务器端,但我很确定在角度前端不需要做任何事情。

标签: angularjs scala google-chrome firefox playframework-2.0


【解决方案1】:

您已证明 Access-Control-Allow-Origin 已在对 OPTIONS 飞行前请求的响应中设置。但是(在我写这篇文章的时候)你没有显示在对 POST 请求本身的响应中设置的标头。由于这是一个容易犯的错误,我冒昧地猜测这就是您的错误所在。

标头需要出现在两个响应中。这意味着,对于您给出的代码,您需要在 controllers.Home.checkPreflightcontrollers.Home.login 中设置标题

【讨论】:

  • 我想没有必要在应用程序的每个端点上添加标头,雇用蚂蚁这样做(然后付钱)或 Instaed 使用过滤器或类似的东西:stackoverflow.com/questions/22144788/…跨度>
猜你喜欢
  • 2015-02-04
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2015-04-29
  • 2016-08-19
  • 2017-08-10
  • 2018-01-15
  • 2019-11-18
相关资源
最近更新 更多