Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Requests between ReactJS Axios and Go API

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 !

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

React now proposes the proxy field in the package.json file to collect and redirect your webapp requests:

"proxy": "http://localhost:8080"

Should do the trick with no cors at all.

See https://create-react-app.dev/docs/proxying-api-requests-in-development/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda