【问题标题】:Proper CORS headers in fetch react获取中的正确 CORS 标头做出反应
【发布时间】:2021-08-31 05:59:56
【问题描述】:

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

我的 react fetch 方法:

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

另外浏览器提示没有标头CORS „Access-Control-Allow-Origin”

【问题讨论】:

    标签: reactjs scala playframework cors


    【解决方案1】:

    allowedOrigins = ["http://localhost:3000"] 应该与您的前端应用程序对应。检查所有路由。 顺便说一句:如果它是公共 API,您可以关闭此过滤器。

    【讨论】:

    • 谢谢先生!我刚刚关闭了过滤器。
    猜你喜欢
    • 2012-04-22
    • 2017-10-08
    • 2018-03-31
    • 2021-03-18
    • 2021-12-05
    • 2019-07-26
    • 1970-01-01
    • 2017-03-23
    • 2022-05-31
    相关资源
    最近更新 更多