2017-09-21 173 views
1

我已经使用gorilla/muxrs/cors设置了我的Go后端。当我尝试发送包含自定义标题(Bearer)的请求时,它将失败。golang预检请求错误

我的服务器设置是这样的:

 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中添加预检要求的条款。

我得到的实际错误:

提取API无法加载http://localhost:8080/profile/tweets。响应 预检申请未通过访问控制检查:没有 “访问控制允许来源”标头出现在请求 资源。原因'http://localhost:4200'因此不允许 访问。如果一个不透明的响应满足您的需求,请将请求的 模式设置为'no-cors'以禁用CORS来获取资源。

谢谢!

+0

是不是'内容Type'而不是'Content_Type'? –

+0

@FrançoisP。这可能是它..我刚刚解决了它,我还需要添加'OptionsPassthrough' –

+0

有用的信息:) –

回答

2

我刚刚解决了这个问题。我不得不通过@Francois P.指出

此外,我不得不添加OptionsPassthroughAllowedHeaders一个错字和OPTIONS方法,像这样:

 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, 
}) 
+0

标记为已接受? – PieOhPah

+0

@PieOhPah我会但我必须等待一段时间;-) –