【发布时间】:2021-06-25 06:46:45
【问题描述】:
我希望你做得很好。 拜托,我使用 Go 和 Gorilla/mux 和 rs/cors 构建了这个 RESTFul API。 这是设置了 cors 的路由器处理程序
func NewRouter() *mux.Router {
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode("I'm alive")
})
r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet, http.MethodOptions) // list all charts
r.HandleFunc("/api/analysis/{projectId}", Create).Methods(http.MethodPost, http.MethodOptions) // create a chart
r.HandleFunc("/api/analysis/{projectId}", Delete).Methods(http.MethodDelete, http.MethodOptions) // delete a chart
return r
}
这是我启动服务器的方式
r := NewRouter()
r.Use(loggingMiddleware)
handler := cors.Default().Handler(r)
log.Fatal(http.ListenAndServe(":5000", handler))
cors 来自https://github.com/rs/cors
从 Angular Web 应用程序中,我调用路由 http://localhost:5000/api/analysis/6023d34440baf5016e5b74ea 但我收到 Cors 错误:PreflightMissingAllowOriginHeader
来自 React.js Web 应用程序,我没有收到任何错误,没有错误!成功请求
我也尝试过来自 MUX https://github.com/gorilla/mux#handling-cors-requests 的 CORS 配置,但它也不起作用。
请问,我做错了什么? 我该如何解决?
【问题讨论】:
-
Angular 应用程序运行在哪个端口上,反应运行在什么端口上? (例如 localhost:3000)
-
Reactjs localhost:9999 - Angular localhost:4200 - Go API localhost:5000
标签: reactjs angular rest go cors