【问题标题】:Go Restful API : CORS configuration works with React but not with AngularGo Restful API:CORS 配置适用于 React 但不适用于 Angular
【发布时间】: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


【解决方案1】:

如果您通过start 命令运行您的 Angular/React 应用程序(或者无论 Angular 运行如何),您可能需要为 CORS 允许的来源指定这些应用程序运行位置的完整 URL(例如 localhost:9999)标题。

还有另外两点:

  1. 从路由的Methods 部分中删除http.MethodOptions - 每当检测到选项HTTP 方法时,CORS 处理程序都会处理它。我认为这些端点永远不会被触发(因为 CORS 处理程序应该拦截它们),但在其中包含 http.MethodOptions 会产生误导。
  2. 您要创建两个路由器吗?首先是r:= mux.NewRouter(),然后是r:= NewRouter() - 或者这只是复制/粘贴的混合?

rs/cors 包可以这样做,如下所示:

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)

如果您需要 cookie:

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)

【讨论】:

  • Christian,关于r := NewRouter(),我刚刚更新了代码
  • 谢谢你的回答,我正准备试试。
  • Christian,抱歉,它不起作用。我仍然遇到来自 Angular Web 应用程序的相同 CORS 问题
  • 我添加了 AllowedHeaders: []string{"*"} 使其工作
  • 这允许任何资源访问 api,您可以从开发人员工具中发布 Angular 应用程序上请求标头的屏幕截图吗?
猜你喜欢
  • 2021-05-29
  • 2018-02-03
  • 2015-01-04
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 2014-07-07
相关资源
最近更新 更多