【问题标题】:Unclear CORS filter in PlayPlay 中的 CORS 过滤器不明确
【发布时间】:2021-10-18 20:19:25
【问题描述】:

我在 Play 中有应用。我的 application.conf 文件是:

include "silhouette.conf"

play.modules.enabled += "modules.SilhouetteModule"


play.filters.enabled += "play.filters.cors.CORSFilter"

play.filters.hosts {
  allowed = ["."]
}

play.filters.cors {
  pathPrefixes = ["/"]
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  allowedHttpHeaders = null
}

所以,我们可以看到所有来源都应该去。

我的前端获取请求如下所示(在 react 应用中):

export function signIn(email, password) {
    const host = "http://localhost:9000/"
    const route = "signIn";
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email, password: password }),
        credentials: 'include',      
    };
    return fetch(host + route, requestOptions)
}

Chrome 显示:

Access to fetch at 'http://localhost:9000/signIn' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

是的,我尝试使用'no-cors',但它仍然不起作用;)非常不清楚,我不知道它是如何工作的以及如何配置它。

【问题讨论】:

  • 我不知道play或者scala但是我知道这个,请加origin: true或者origin: ['http://localhost:3000']

标签: reactjs scala playframework fetch silhouette


【解决方案1】:

事情是这样的,我从 play 框架文档中得到

play.filters.cors {
  pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://www.example.com", ...] <-- Add your localhost url here
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

文档:https://www.playframework.com/documentation/2.8.x/CorsFilter

【讨论】:

  • 它不起作用我多次研究Play文档:/
【解决方案2】:

在我看来,Play 默认添加了 CSRF 过滤器。在路由文件中添加+nocsrf 后一切正常。这很奇怪而且不清楚。

# Authentication
+nocsrf
POST        /signUp                                   controllers.SignUpController.signUp
+nocsrf
POST        /signIn                                   controllers.SignInController.signIn
+nocsrf
POST        /signOut                                  controllers.SignInController.signOut

【讨论】:

  • 你自己解决了你的问题,很好
  • 当然感谢您的努力,并为您的回答指出了点:) 无论如何,Play 非常不清楚,也没有社区。​​span>
猜你喜欢
  • 1970-01-01
  • 2016-08-19
  • 2014-03-14
  • 1970-01-01
  • 2017-09-14
  • 2014-08-14
  • 2017-08-10
  • 2019-01-12
  • 2015-03-28
相关资源
最近更新 更多