【问题标题】:Go CORS issue no responseGo CORS 发出无响应
【发布时间】:2021-04-20 01:02:23
【问题描述】:

我有一个使用 fetch 调用 go mux api 的 React 应用程序。

我很清楚这里的问题:Making golang Gorilla CORS handler work

但这对我不起作用。我已经尝试了该帖子中的所有内容,但仍然没有成功。看起来 go 甚至没有为我运行任何中间件或路由处理函数。

这是我尝试修复它的第一种方法。这使用gorilla/handlers

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func commonMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("MIDDLEWARE CALLED")

        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

        next.ServeHTTP(w, r)
    })
}

func ApiHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("ROUTE CALLED")
    fmt.Fprintf(w, `{"works:"true}`)
}

func main() {
    var router *mux.Router = mux.NewRouter()
    router.Use(commonMiddleware)

    router.HandleFunc("/api", ApiHandler).Methods("POST")

    headersOk := handlers.AllowedHeaders([]string{"Access-Control-Allow-Origin", "Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin"})
    originsOk := handlers.AllowedOrigins([]string{"http://localhost:*", "*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

    http.ListenAndServe(":8000", handlers.CORS(headersOk, originsOk, methodsOk)(router))
}

这里使用rs/cors

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/rs/cors"
)

func commonMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("MIDDLEWARE CALLED")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

        next.ServeHTTP(w, r)
    })
}

func ApiHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("ROUTE CALLED")
    fmt.Fprintf(w, `{"works:"true}`)
}

func main() {
    var router *mux.Router = mux.NewRouter()
    router.Use(commonMiddleware)

    router.HandleFunc("/api", ApiHandler).Methods("POST")

    c := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"},
        AllowCredentials: true,
    })

    handler := c.Handler(router)

    http.ListenAndServe(":8000", handler)
}

但是,在这两种情况下,浏览器中仍会出现 CORS 错误。我在 5000 端口上运行 react 服务器,而 go 服务器在 8000 端口上。

 fetch("http://localhost:8000/api", {
               method: 'POST',
               headers: {
                    // "Access-Control-Allow-Origin": "*",
                    'Content-Type': 'application/json'
               },
               body: JSON.stringify({
                    example: 1
               })
          })

Chrome 中的错误:

Access to fetch at 'http://localhost:8000/validate/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这两种解决方案都不起作用。实际上“MIDDLEWARE CALLED”和“ROUTE CALLED”在 go 中永远不会打印出来。该 api 在 Postman 中工作得很好,所以我知道路由器工作得很好,问题确实是 CORS。所以看起来这条路线永远不会被调用。

这太棒了,它可能与预检有关吗?如何禁用所有 cors 问题?

【问题讨论】:

  • 来自浏览器的 CORS 错误是针对 /validate/,您提供的代码中没有任何内容表明您的代码可以处理该端点。

标签: go cors preflight mux


【解决方案1】:

如果您想允许所有来源,另一种方法是

c := cors.New(cors.Options{
        AllowOriginFunc: func(r string) bool {
                             return true
                         }
    })

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。问题出在我的防病毒软件中。禁用它可以解决问题。

    【讨论】:

      猜你喜欢
      • 2016-08-05
      • 2021-08-31
      • 1970-01-01
      • 2012-06-04
      • 2014-08-04
      • 2018-05-02
      • 2017-04-25
      • 2016-01-24
      • 2019-10-21
      相关资源
      最近更新 更多