【发布时间】:2023-04-03 18:08:02
【问题描述】:
我已经使用 gorilla/mux 和 rs/cors 设置了我的 Go 后端。当我尝试发送包含自定义标头 (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/mux 和 rs/cors。
我得到的实际错误:
Fetch API 无法加载 http://localhost:8080/profile/tweets。回复 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 使用权。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。
谢谢!
【问题讨论】:
-
不是
Content-Type而不是Content_Type吗? -
@FrançoisP。原来是这样。。其实我刚刚解决了,还需要加
OptionsPassthrough -
很高兴知道:)
-
@FrançoisP。谢谢你的评论! :-)