我有一个React应用程序,使用fetch调用go mux api。但这对我不起作用。我已经尝试了该帖子中的所有内容,但仍然没有成功。看起来go甚至没有为我运行任何中间件或路由处理程序函数。这是我尝试修复它的第一种方法。这使用gorilla/handlerspackage mainimport ( "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))}这两种解决方案都不起作用。事实上,“中间件调用”和“路由调用”在去从不打印出来。API在Postman中工作正常,所以我知道路由器工作正常,问题真的是CORS。因此,该路线似乎从未被调用。这令人惊叹,它可能与印前检查有关。如何禁用所有 cors 问题?
- 2 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消