【问题标题】:golang preflight request errorgolang预检请求错误
【发布时间】:2023-04-03 18:08:02
【问题描述】:

我已经使用 gorilla/muxrs/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/muxrs/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。谢谢你的评论! :-)

标签: go cors mux


【解决方案1】:

我刚刚解决了这个问题。正如@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,
})

【讨论】:

  • @PieOhPah 我会,但我必须等待一段时间 ;-)
猜你喜欢
  • 2020-07-07
  • 2018-02-28
  • 2015-08-10
  • 2020-10-26
  • 1970-01-01
  • 2019-04-11
  • 2017-05-06
  • 2021-08-25
  • 2019-10-03
相关资源
最近更新 更多