英文:
CORS not working even though OPTIONS returns HTTP 200
问题
我正在使用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)
}
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)
})
}
在网络选项卡中看起来像这样:
英文:
I am using chi and have setup cors as follows
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)
}
My Cors
middleware
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)
})
}
In network tab it looks like:
答案1
得分: 3
你刚刚错误地输入了标题名称:
w.Header().Set("Allow-Control-Allow-Origin", "*")
^^^^^
在那里,你需要使用Access-Control而不是Allow-Control:
w.Header().Set("Access-Control-Allow-Origin", "*")
当然,对于你设置的其他三个标题也是一样的。
英文:
You just mistyped the header names:
w.Header().Set("Allow-Control-Allow-Origin", "*")
^^^^^
Instead of Allow-Control there, you need Access-Control:
w.Header().Set("Access-Control-Allow-Origin", "*")
…and same of course for the other three headers you’re setting there.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论