我正在使用 chi 并有如下设置 cors
func main() {
r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Use(Cors)
r.Post("/auth/login", Login)
r.Route("/ec2", func(r chi.Router) {
r.Use(Cors)
r.Get("/", ListEc2)
})
http.ListenAndServe(":9000", r)
}
我的Cors
中间件
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Allow-Control-Allow-Origin", "*")
w.Header().Set("Allow-Control-Allow-Methods", "*")
w.Header().Set("Allow-Control-Allow-Headers", "*")
w.Header().Set("Allow-Control-Allow-Credentials", "true")
log.Printf("Should set headers")
if r.Method == "OPTIONS" {
log.Printf("Should return for OPTIONS")
return
}
next.ServeHTTP(w, r)
})
}
在网络选项卡中,它看起来像: