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

即使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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流