score:4

Accepted answer

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

score: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/


Related Query

More Query from same tag