dsi36131
2017-06-08 08:35
浏览 1.0k
已采纳

即使OPTIONS返回HTTP 200,CORS也不起作用

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:

enter image description here

图片转代码服务由CSDN问答提供 功能建议

我正在使用chi并按如下所示设置cors

   func main(){
r:= chi.NewRouter()
 r.Use(render.SetContentType(render.ContentTypeJSON))
 r.Use(Cors)
 
 r.Post(“ / auth / login  “,登录)
 r.Route(” / ec2“,func(r chi.Router){
 r.Use(Cors)
 r.Get(” /“,ListEc2)
})
 \  n http.ListenAndServe(“:9000”,r)
} 
   
 
 

我的 Cors 中间件

  func Cors(下一个http.Handler)http.Handler {
返回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(”应设置标题“)
 \  n如果r.Method ==“ OPTIONS” {
 log.Printf(“应该为OPTIONS返回”)
返回
  } 
 next.ServeHTTP(w,r)
})
} 
   
 
 

在“网络”标签中,它看起来像:

”在此处输入图片描述“

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqk77945 2017-06-08 08:44
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题