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 !