[英]HTTP Request to external API works with .NET, but not with React (CORS problems)
[英]Go Restful API : CORS configuration works with React but not with Angular
我希望你做得很好。 拜托,我有这个 RESTFul API 使用 Go 和 Gorilla/mux 和 rs/cors 构建。 这是设置了 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
From an Angular Web application, I'm calling the route http://localhost:5000/api/analysis/6023d34440baf5016e5b74ea but I receive a Cors error: PreflightMissingAllowOriginHeader
从 React.js Web 应用程序,我没有收到任何错误,没有错误! 请求成功
我也尝试过来自 MUX https://github.com/gorilla/mux#handling-cors-requests的 CORS 配置,但它也不起作用。
请问,我做错了什么? 我该如何解决?
If you are running your angular/react apps via the start
command (or however angular is run) you may need to specify the full URL of where these apps are running (eg localhost:9999
) for the CORS allowed origins header.
还有另外两点:
Methods
部分中删除http.MethodOptions
- 每当检测到选项 HTTP 方法时,CORS 处理程序将处理它。 我认为这些端点永远不会被触发(因为 CORS 处理程序应该拦截它们),但是在其中http.MethodOptions
会产生误导。r:= mux.NewRouter()
然后再使用r:= NewRouter()
- 或者这只是复制/粘贴的混合? 这可以为rs/cors
package 完成,如下所示:
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet)
// ... add other routes here
// Then wrap in the CORS handler
corsHandler := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost", "http://localhost:4200", "HTTP://localhost:9999"},
AllowedHeaders: []string{"*"},
}).Handler(r)
// Now serve the API
http.ListenAndServe(":5000", corsHandler)
如果您需要 cookies:
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet)
// ... add other routes here
// Then wrap in the CORS handler
corsHandler := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost", "http://localhost:4200", "HTTP://localhost:9999"},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
}).Handler(r)
// Now serve the API
http.ListenAndServe(":5000", corsHandler)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.