doupo5178 2019-08-16 13:34
浏览 536

在golang服务器中面临CORS问题

I have written this code in my Go server:

func main() {
    r := chi.NewRouter()
    cors := cors.New(cors.Options{
        AllowedOrigins:     []string{"*"},
        AllowOriginFunc:    func(r *http.Request, origin string) bool { return true },
        AllowedMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowedHeaders:     []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
        ExposedHeaders:     []string{"Link"},
        AllowCredentials:   true,
        OptionsPassthrough: true,
        MaxAge:             3599, // Maximum value not ignored by any of major browsers
    })
    flag.Parse()

    // A good base middleware stack
    r.Use(cors.Handler)
    r.Use(middleware.RequestID)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)
    r.Use(middleware.URLFormat)
    r.Use(render.SetContentType(render.ContentTypeJSON))
    r.Use(middleware.Timeout(60 * time.Second))

    r.Group(func(r chi.Router) {

        r.Route("/api", func(r chi.Router) {
            r.Route("/items", func(r chi.Router) {
                r.Get("/", allItems)
                r.Route("/{barcode}", func(r chi.Router) {
                    r.Get("/", getItem)
                    r.Put("/", updateItem)
                })
                r.Post("/", postItem)
                r.Delete("/", deleteItem)
            })

            r.Route("/sale_lines", func(r chi.Router) {
                //  r.Use(cors.Handler)
                r.Post("/", postSales)
                r.Put("/", updateSales)
                r.Delete("/", deleteSales)

            })
        })
    })
    http.ListenAndServe(":8080", r)
}

I am facing the problem that when I am calling the api from my react app, it is giving me an error like this:

Access to XMLHttpRequest at 'http://localhost:8080/api/sale_lines' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

What problem is there which I am missing?

  • 写回答

1条回答 默认 最新

  • doujing3896 2019-08-17 04:40
    关注

    Your mistake must be in some of your middleware. The probe and your code works fine, just change the name of AllowOriginFunc from the CORS options to AllowOriginRequestFunc

    Server code:

    package main
    
    import (
        "net/http"
    
        "github.com/go-chi/chi"
        "github.com/rs/cors"
    )
    
    func main() {
        r := chi.NewRouter()
        cors := cors.New(cors.Options{
            AllowedOrigins:         []string{"*"},
            AllowOriginRequestFunc: func(r *http.Request, origin string) bool { return true },
            AllowedMethods:         []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
            AllowedHeaders:         []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
            ExposedHeaders:         []string{"Link"},
            AllowCredentials:       true,
            OptionsPassthrough:     true,
            MaxAge:                 3599, // Maximum value not ignored by any of major browsers
        })
    
        r.Use(cors.Handler)
    
        r.Get("/", func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Hello World"))
        })
        http.ListenAndServe(":8080", r)
    }
    

    I tested it using XMLHttpRequest:

    <div id="root"></div>
    <script>
      var req = new XMLHttpRequest();
      req.open("GET", "http://localhost:8080/", false);
      req.onload = function(event) {
        if (req.readyState == 4 && req.status == 200)
          document.getElementById("root").innerText = req.responseText;
      };
      req.send();
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序