在golang服务器中面临CORS问题

时间:2019-08-16 13:34:32

标签: http go cors

我已经在Go服务器中编写了以下代码:

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)
}

我遇到的问题是,当我从我的react应用程序调用api时,它给了我这样的错误:

  

从原点“ http://localhost:8080/api/sale_lines”到“ http://localhost:3000”的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。

我缺少什么问题?

1 个答案:

答案 0 :(得分:1)

您的错误一定是在某些中间件中。该探针和您的代码可以正常工作,只需将AllowOriginFunc的名称从CORS选项更改为AllowOriginRequestFunc

服务器代码:

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)
}

我使用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>