适当的 CORS headers 在 fetch 反应中

Proper CORS headers in fetch react

我有自己的 API 用 Play Scala 写的,前端客户端用 react.js 写的 我无法发送注销请求(我使用 OAuth2),因为我收到 cors headers 错误。我试图修复它,但我不能。

我的反应获取方法:

function signOut() {
    const host = "http://localhost:9000/"
    const route = "signOut";
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json','Access-Control-Allow-Origin': '*'},
        credentials: 'include',
        mode: 'cors',
    };
    return fetch(host + route, requestOptions).then((response) => response.json())
}

我的 scala play application.conf:

play.filters {

  # Enabled filters are run automatically against Play.
  # CSRFFilter, AllowedHostFilters, and SecurityHeadersFilters are enabled by default.
  enabled += filters.ExampleFilter
  enabled += play.filters.cors.CORSFilter
  # Disabled filters remove elements from the enabled list.
  #disabled += filters.ExampleFilter
}

enables += play.filter.cors.CorsFilter
  cors {
    # Filter paths by a whitelist of path prefixes
    #pathPrefixes = ["/some/path", ...]

    # The allowed origins. If null, all origins are allowed.
    #allowedOrigins = ["https://www.example.com"]
    allowedOrigins = ["http://localhost:3000"]
    # The allowed HTTP methods. If null, all methods are allowed
    #allowedHttpMethods = ["GET", "POST"]
        allowedHttpMethods = ["GET", "POST", "PUT", "PATCH", "OPTION", "DELETE"]
  }

我的浏览器错误:

XHROPTIONShttp://localhost:9000/signOut

而且浏览器显示没有 header CORS „Access-Control-Allow-Origin”

allowedOrigins = ["http://localhost:3000"] 应该对应你的前端 app.Check 所有路由。 BETWEEN:如果它是 public API 您可以关闭此过滤器。