我有一個React應用程序,使用fetch調(diào)用go mux api。但這對我不起作用。我已經(jīng)嘗試了該帖子中的所有內(nèi)容,但仍然沒有成功。看起來go甚至沒有為我運行任何中間件或路由處理程序函數(shù)。這是我嘗試修復它的第一種方法。這使用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))}這兩種解決方案都不起作用。事實上,“中間件調(diào)用”和“路由調(diào)用”在去從不打印出來。API在Postman中工作正常,所以我知道路由器工作正常,問題真的是CORS。因此,該路線似乎從未被調(diào)用。這令人驚嘆,它可能與印前檢查有關(guān)。如何禁用所有 cors 問題?
- 2 回答
- 0 關(guān)注
- 112 瀏覽
添加回答
舉報
0/150
提交
取消