flutter web 的 http 请求被 Cors 策略阻止

Kav*_*gar 7 flutter flutter-web

我有一个 Android、Ios 和 Web 应用程序,使用 php 作为后端。所有 Api 在 android 和 ios 中都工作正常,但在 web 中抛出 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 扩展,网络将运行顺利。请帮帮我

ישו*_*ותך 6

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

从源“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.")
    }
}
Run Code Online (Sandbox Code Playgroud)