drn1008 2017-09-21 20:21
浏览 173
已采纳

golang飞行前请求错误

I have set up my Go backend using gorilla/mux and rs/cors. When I try to send a request including a custom header (Bearer) it fails.

My server setup looks like this:

     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))

I have tried various other solutions (such as adding OPTIONS in the Methods call. The endpoint for which I am trying to pass the Bearer token is the /profile/tweets endpoint.

I'm unsure how to continue with gorilla/mux and rs/cors in terms of adding the preflight request.

The actual error that I get:

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.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongruo0909 2017-09-21 23:34
    关注

    I've just solved the problem. I had a typo in the AllowedHeaders as pointed out by @Francois P.

    In addition, I had to add OptionsPassthrough and the OPTIONS method, like so:

         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,
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器