当前位置: 首页 > 知识库问答 >
问题:

http请求被用于Flatter web的Cors策略阻止

鲍高扬
2023-03-14

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

访问位于“”的XMLHttpRequesthttps://example.com/api“起源”http://localhost:49168'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。

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

共有1个答案

孔琪
2023-03-14

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

访问位于“”的XMLHttpRequesthttps://example.com/api“起源”http://localhost:49168'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。

它说了一些关于请求的事情,但事实证明它与请求无关。而且它也与Web服务器无关(在我的例子中,apachenginx)。

解决方案是从后端向响应(是,响应)添加头。我不知道phpcode的解决方案,但我在我的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.")
    }
}
 类似资料:
  • 当我使用HTML2Canvas评估图像时,我得到了这个错误。 CORS策略阻止从来源“http://localhost:8080”访问位于“http://testdomain.com/storage/images/products/user_front.png”的映像:请求的资源上没有“Access-Control-Allow-Origin”标头。 下面是我的cors配置。 有人能帮我吗?

  • 有一个应用程序在角7也有一个. net web api解决方案,当我调用一个动作CORS问题发生,错误如下 CORS策略阻止从http://localhost:57467/UserDetails/GetUserDetailshttp://localhost:4200访问XMLHttpRequest:对预试请求的响应不通过权限改造检查:请求的资源上不存在访问控制允许起源标头。 我试图使用Web ap

  • 我有一个flask socketio服务器,运行在带有nginx的ubuntu上。我有一个客户端调用服务器。当我尝试呼叫服务器时,收到以下错误: 这是我对烧瓶的初始化: ... 这是我当前在nginx中的配置: 来自客户端对服务器的请求如下所示: 我尝试过: -添加允许CORS到位置/仅,以及两者-在烧瓶应用程序中删除/添加allow CORS origin。 有人能帮忙吗?

  • 我有一个。NET核心应用程序,它有一个REST API被一个角客户机使用,但遇到了CORS问题。 但仍在客户端(运行在本地端口4200上)中获取错误: CORS策略阻止从来源“HTTP://localhost:4200”访问位于“HTTP://localhost/myapi/api/table”的XMLHttpRequest:对飞行前请求的响应没有通过访问控制检查:它没有HTTP ok状态。