golang 预检请求错误

golang preflight request error

我已经使用 gorilla/muxrs/cors 设置了我的 Go 后端。当我尝试发送包含自定义 header (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))

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

我不确定如何继续 gorilla/muxrs/cors 添加预检请求。

我得到的实际错误:

Fetch API cannot load http://localhost:8080/profile/tweets. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

谢谢!

我刚刚解决了这个问题。正如@Francois P.

所指出的,我在 AllowedHeaders 中有一个错字

此外,我必须添加 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,
})