gpt4 book ai didi

angularjs - 在 Angular + Scala Play 上启用 CORS

转载 作者:行者123 更新时间:2023-12-01 12:41:28 24 4
gpt4 key购买 nike

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

这是我在前端的请求。基本上它是一个 POST发送带有 userName 的 JSON和 password领域。

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.

此外,我的 promise (将 POST 称为 /login )被拒绝,即我添加了一个 console.log成功案例和失败案例。

最佳答案

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

两个响应中都需要存在 header 。这意味着,对于您提供的代码,您需要在 controllers.Home.checkPreflight 中设置标题和 controllers.Home.login

关于angularjs - 在 Angular + Scala Play 上启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com