Home > Blockchain >  Requests between ReactJS Axios and Go API
Requests between ReactJS Axios and Go API

Time:09-17

I have a ReactJS app running on a NodeJS server with Express that I used because I needed to sync my front and back routers. I'm also using a Go API using Chi that works fine (I've done tests with postman and it is actually working). To send requests to my Go API from ReactJS I use Axios but I have an error in my console:

Access to XMLHttpRequest at 'http://localhost:8080/api/connection/getToken' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But I've already done some changes on both my Axios request and my Golang API code.

Here is my ReactJS Axios request:

    axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
        axios.get('http://localhost:8080/api/connection/getToken', {  
            headers: {
                 'Access-Control-Allow-Origin': true,
                 code: code,
                } 
        }).then(res => console.log(res));

Here is my Go code:

    func connectInit(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        if r.Header.Values("code") != nil {
            code := r.Header.Get("code")
            clientToken, err := getClientToken(code)
            if err != nil {
                fmt.Fprint(w, err.Error())
            }
            fmt.Fprint(w, clientToken)

        }
    }

Here is my Chi router in Go:

    func ConnexionRoutes() *chi.Mux {
        router := chi.NewRouter()
        router.Get("/getToken", connectInit)
        return router
    }

Thank you !

CodePudding user response:

the problem you have is that the go server is served on the origin http://localhost:8080

while the react local webapp is certainly served on the origin http://localhost:3000 (this is what I have most of the time)

According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin the origin (in the sense of the browser) is:

<scheme> "://" <hostname> [ ":" <port> ]

the browser detects the JS react webapp is trying to access another origin (port 8080) that has no specific header and therefore blocking it.

One solution to this is to configure the go API so that it returns the appropriate header Access-Control-Allow-Origin: *.

Even better, for chi, I personnaly use:

import "github.com/go-chi/cors"

router := chi.NewRouter()
router.Use(cors.AllowAll().Handler)

More about CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

  • Related