Play 中的 CORS 过滤器不明确

Unclear CORS filter in Play

我在 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 框架文档中得到

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 默认添加了 CSRF 过滤器。在路由文件中添加 +nocsrf 后一切正常。很奇怪也不清楚。

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