首页 > 解决方案 > http 请求被 Flutter Web 的 Cors 策略阻止

问题描述

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

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

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

标签: flutterflutter-web

解决方案


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

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

它说了一些关于请求的内容,但事实证明它与请求无关。apache它也与网络服务器(或nginx在我的情况下)无关。

解决方案是从后端向响应(是的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.")
    }
}

推荐阅读