Has been blocked by CORS policy: Response to preflight request doesn't pass access control check:

has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

I have created trip server, It works fine and we are able to make post request by Insomnia but when we make POST request by axios on our fron-end it sends an error

our request on axios

let config = {
  headers: {
    "Content-Type": "application/json",
    'Access-Control-Allow-Origin': '*',
  }
}

let data = {
  "id": 4
}
  
axios.post('http://196.121.147.69:9777/twirp/route.FRoute/GetLists', data, config)
  .then((res) => {
    console.log(res)
  })
  .catch((err) => {
    console.log(err)
  });
} 

my go file

func setupResponse(w *http.ResponseWriter, req *http.Request) {
   (*w).Header().Set("Access-Control-Allow-Origin", "*")
   (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
   (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}


func WithUserAgent(base http.Handler) http.Handler {
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

	  ctx := r.Context()
	  ua := r.Header.Get("Jwt")
	  ctx = context.WithValue(ctx, "jwt", ua)
	
	  r = r.WithContext(ctx)

     setupResponse(&w, r)
	  base.ServeHTTP(w, r)
})
 }

const (
host     = "localhost"
port     = 5432
user     = "postgres"
password = "postgres"
dbname   = "postgres"
)

func main() {


psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
	"password=%s dbname=%s sslmode=disable",
	host, port, user, password, dbname)

   server := &s.Server{psqlInfo}

   twirpHandler := p.NewFinanceServiceServer(server, nil)

      wrap := WithUserAgent(twirpHandler)
  log.Fatalln(http.ListenAndServe(":9707", wrap))

}

And the error message is ?
I am not sure but the port you specify (9707) in your go code is not the same in the axios call(9777)…

error message

has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

I solved it with wrapping my code into Gorilla’s handler

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.