golang 预检请求错误

Dyl*_*eus 3 go mux cors

我已经使用gorilla/muxand设置了我的 Go 后端rs/cors。当我尝试发送包含自定义标头 ( Bearer)的请求时,它失败了。

我的服务器设置如下所示:

     router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/users", GetUsers).Methods("GET")
router.HandleFunc("/", GetUsers).Methods("GET")
router.HandleFunc("/tweets", GetTweets).Methods("GET")
router.HandleFunc("/login", Login).Methods("POST")
router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET")

c := cors.New(cors.Options{
    AllowedOrigins: []string{"*"},
    AllowedMethods: []string{"GET", "POST", "PATCH"},
    AllowedHeaders: []string{"Bearer", "Content_Type"},})

handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8080", handler))
Run Code Online (Sandbox Code Playgroud)

我尝试了各种其他解决方案(例如OPTIONSMethods调用中添加。我尝试为其传递Bearer令牌的/profile/tweets端点是端点。

我不确定如何继续gorilla/mux以及如何rs/cors添加预检请求。

我得到的实际错误:

Fetch API 无法加载http://localhost:8080/profile/tweets。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:4200 '。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

谢谢!

Dyl*_*eus 7

我刚刚解决了这个问题。AllowedHeaders正如@Francois P. 指出的那样,我有一个错字。

另外,我必须添加OptionsPassthroughOPTIONS方法,如下所示:

     router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET","OPTIONS")

c := cors.New(cors.Options{
    AllowedMethods: []string{"GET","POST", "OPTIONS"},
    AllowedOrigins: []string{"*"},
    AllowCredentials: true,
    AllowedHeaders: []string{"Content-Type","Bearer","Bearer ","content-type","Origin","Accept"},
    OptionsPassthrough: true,
})
Run Code Online (Sandbox Code Playgroud)