在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?

duanou9758
duanou9758 我从邮递员那里检查了一下,它返回了我的正常状态,但是我的React应用仍然向我显示上述错误
大约一年之前 回复
donglian1982
donglian1982 它所指的“预检请求”是HTTPOPTIONS请求;基本上,错误是说当它发出原始OPTIONS请求以查看是否允许CORS时,它没有得到200的返还,而是得到了其他东西。您可以通过使用curl或Postman之类的东西向该URL发出一个OPTIONS请求来找出其确切响应,从而找出问题的答案,这可以缩小问题范围。
大约一年之前 回复
douyiyang6317
douyiyang6317 也请格式化您的代码以使其易于阅读。
大约一年之前 回复

1个回答

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>
dongwu5801
dongwu5801 我使用的版本是v1.0.7
大约一年之前 回复
doubingqi5829
doubingqi5829 我实现了您的建议,但它给了我这个错误:cors类型的结构文字中的未知字段'AllowOriginRequestFunc'
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐