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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化