【发布时间】:2019-10-25 07:46:58
【问题描述】:
现在我正在使用标准库 net/http 在 Go 上编写一个简单的服务器。服务器放置在 docker 容器中,并放置在 google cloud paltform 上。但是,当我想从我的第三方 React 应用程序(位于不同的服务器上)访问服务器时,我总是会收到 CORS 错误。
在线寻找解决方案,我在代码中添加了一个库,旨在解决СORS问题。但是添加一个库并没有帮助。即使在其应用之后,服务器也不会向我发送СORS 标头。我现在有什么代码?
package main
import (
controller "./controllers"
"./util"
"github.com/gorilla/mux"
"github.com/rs/cors"
"log"
"net/http"
//"os"
)
// Entry point
func main() {
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // All origins
AllowedMethods: []string{"GET"}, // Allowing only get, just an example
AllowedHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
Debug: true,
})
r := mux.NewRouter()
// Router
// Live check
r.HandleFunc("/live", controller.LiveCheck)
apiRouter := r.PathPrefix("/api").Subrouter()
// Medication data
medicationRouter := apiRouter.PathPrefix("/medication").Subrouter()
medicationRouter.HandleFunc("", controller.MedicationHeadersList).Methods("GET")
medicationRouter.HandleFunc("/{id}", controller.MedicationChildrenList).Methods("GET")
medicationRouter.HandleFunc("/{id}/leafs", controller.MedicationLeafsList).Methods("GET")
medicationRouter.HandleFunc("/search/", controller.SearchMedicationList).Methods("GET")
medicationRouter.HandleFunc("/result/{id}", controller.MedicationSearchResult).Methods("GET")
//r.Use(util.CORS)
apiRouter.Use(util.VerifyToken)
log.Println(http.ListenAndServe(":8080", c.Handler(r)))
}
这是我从浏览器控制台中得到的答案:
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 35.190.37.37:80
Referrer Policy: no-referrer-when-downgrade
Content-Length: 0
Date: Mon, 10 Jun 2019 22:37:36 GMT
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Via: 1.1 google
我还尝试手动设置 CORS 标头,创建一个中间件,但它也没有帮助。 提前感谢您的帮助!
UPD感谢大家的回答和帮助。一切都变得容易多了。谷歌没有更新我的 docker 容器,所以我对代码的所有更改都没有达到预期的效果。我在问题描述中给出的代码完美地解决了 CORS 的问题。该问题可以视为已结束。
【问题讨论】:
标签: google-app-engine go google-cloud-platform