【问题标题】:http request is blocked by Cors policy for flutter webhttp 请求被 Flutter Web 的 Cors 策略阻止
【发布时间】:2021-05-19 05:07:31
【问题描述】:

我有一个使用 php 作为后端的 Android、Ios 和网络应用程序。所有 Api 在 android 和 ios 中都运行良好,但在 web.xml 中抛出 CORS 错误。 出现这样的错误

CORS 策略已阻止从源“http://localhost:49168”访问“https://example.com/api”处的 XMLHttpRequest:不存在“Access-Control-Allow-Origin”标头请求的资源。

我尝试发送 标头:{'Access-Control-Allow-Origin': 'http://localhost:49168', “来源”:“http://localhost:49168” }, 到http请求。 如果我为 chrome 添加 CORS 扩展,Web 工作顺利。请帮帮我

【问题讨论】:

  • 我正在使用表单数据。我应该在哪里添加这些请求?
  • 您的 API 需要发送访问控制允许来源“您的域”/“*”标头。我建议阅读 CORS developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • 我已经发送了 post 请求但是抛出了同样的错误
  • CORS 不是您从前端 (Flutter) 控制的东西。您的 PHP API 必须发送这些标头。我发送的链接中对此进行了概述。

标签: flutter flutter-web


【解决方案1】:

两周前我遇到了同样的问题。对我来说,以下错误给了我检查问题的错误方向:

从源访问“https://example.com/api”处的 XMLHttpRequest 'http://localhost:49168' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

它说明了请求,但事实证明它与请求无关。它也与网络服务器无关(在我的例子中是apachenginx)。

解决方案是在后端的响应中添加标头(是的,response)。我不知道 php 代码的解决方案,但我在我的 golang 后端使用以下代码将标头添加到响应中:

// Adding CORS header to response.
func (server *WebUploadServer) addCorsHeader(res http.ResponseWriter) {
    headers := res.Header()
    // use your domain or ip address instead of "*".
    // Using "*" is allowing access from every one
    // only for development.
    headers.Add("Access-Control-Allow-Origin", "*")
    headers.Add("Vary", "Origin")
    headers.Add("Vary", "Access-Control-Request-Method")
    headers.Add("Vary", "Access-Control-Request-Headers")
    headers.Add("Access-Control-Allow-Headers", "Content-Type, Origin, Accept, token")
    headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
}


// Here we handle the web request.
func (server *WebUploadServer) webHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Endpoint hit")

    server.addCorsHeader(w) // Here, we add the header to the response

    switch r.Method {
    case "POST":
        // do something here.
    case "OPTIONS":
        w.WriteHeader(http.StatusOK)
    case "GET":
        fallthrough
    default:
        fmt.Fprintf(w, "Sorry, only  POST method is supported.")
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2019-11-30
    • 2019-10-01
    • 2021-09-05
    • 2021-02-28
    • 2021-10-25
    • 2021-12-17
    • 1970-01-01
    • 2022-06-26
    相关资源
    最近更新 更多