简体   繁体   中英

facing cors issue in golang server

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM