Cors problem in deployment (react + go)
streamerd
TRIALOP

2 years ago

Helo people, I'm aware there's been bunch of similar issue presented and resolved, yet I did all I could and still no luck.

project ID:

443e27d8-9cdf-478d-a4ec-c846823facf8

I'm getting

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.diplomacy.network/peace. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 405.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.diplomacy.network/peace. (Reason: CORS request did not succeed). Status code: (null)..

I got below config in go:

corsMiddleware := handlers.CORS(
        handlers.AllowedOrigins([]string{
            "https://diplomacy.network",
            "http://localhost:3000",
        }),
        handlers.AllowedMethods([]string{
            http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions, // Specify allowed methods
        }),
        handlers.AllowedHeaders([]string{
            "Content-Type", "Access-Control-Allow-Origin",
        }),
    )

and making request like below from the react:

(to https url)

      const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/peace`;
      console.log("API URL:", apiUrl);
      await axios.post(apiUrl, {
        peacemakers: [updatedPeacemaker, peacemakers[1]],
      });
      alert("Update successful!");
    } catch (error) {
      console.error("Error sending POST request:", error);
      alert("Failed to update.");
    }```

21 Replies

2 years ago

what is NEXT_PUBLIC_API_URL set to?


streamerd
TRIALOP

2 years ago


streamerd
TRIALOP

2 years ago

without trailing /


2 years ago

have you confirmed that headers are being set locally?


streamerd
TRIALOP

2 years ago

no headers set by the react explicitly, but seeing some req headers set on the browser ( @ local)

1248731165528035430

1248731166123495424


2 years ago

react is a framework, its not going to be setting headers, can you elaborate on what you mean by that?


streamerd
TRIALOP

2 years ago

all the headers we got are set automatically by the browser. none I've additionally set via axios library


2 years ago

im sorry but that isnt answering the questions ive asked


2 years ago

have you confirmed that CORS headers are being set locally?


streamerd
TRIALOP

2 years ago

I haven't manualy set any so far. But now I've set below and didn't change anything.


    headers: {
            "Content-Type": "application/json", 
            Accept: "application/json",
          },

2 years ago

This also does not answer the question, im not sure where the confusion is coming from?


2 years ago

ill try to clarify further, have you confirmed that your go backend setting the cors headers when testing locally?


streamerd
TRIALOP

2 years ago

yes locally my go backend sets access-control-allow origin as localhost:3000 (my react app) successfully.

1248750535222493286


streamerd
TRIALOP

2 years ago

and that's not the case when I switch to prod endpoint

1248750935354769509


streamerd
TRIALOP

2 years ago

would that be a revelant response @Brody ?


2 years ago

what go web framework and middleware for cors are you using? I'll try to get a reproducible example going


streamerd
TRIALOP

2 years ago


2 years ago

I thought gorilla had an easy way to chain middlewares


2 years ago

With this code I am unable to repduce the issue as long as I am specifying https://renewed-warmth-production.up.railway.app in the Origin header when making a request.

package main

import (
    "cmp"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"
)

func main() {
    log.Println("Configuring CORS")

    port := cmp.Or(os.Getenv("PORT"), "3030")

    corsMiddleware := handlers.CORS(
        handlers.AllowedOrigins([]string{
            "https://renewed-warmth-production.up.railway.app",
            "http://localhost:" + port,
            "http://127.0.0.1:" + port,
        }),
        handlers.AllowedMethods([]string{
            http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions, // Specify allowed methods
        }),
        handlers.AllowedHeaders([]string{
            "Content-Type", "Access-Control-Allow-Origin",
        }),
    )

    wrapperTest := func(w http.ResponseWriter, r *http.Request) {
        handler := corsMiddleware(http.HandlerFunc(handleTest))
        handler.ServeHTTP(w, r)
    }

    http.HandleFunc("GET /test", wrapperTest)
    http.HandleFunc("POST /test", wrapperTest)

    log.Fatal(http.ListenAndServe(":"+port, nil))
}

func handleTest(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, world!"))
}

1249410772468240444


2 years ago

Here is the code I used, I was not able to reproduce the issue, even with cloudflare in front -


import (
    "cmp"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"
)

func main() {
    log.Println("Configuring CORS")

    corsMiddleware := handlers.CORS(
        handlers.AllowedOrigins([]string{
            "https://renewed-warmth-production.up.railway.app",
            "http://localhost:3000",
            "http://127.0.0.1:3000",
        }),
        handlers.AllowedMethods([]string{
            http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions,
        }),
        handlers.AllowedHeaders([]string{
            "Content-Type", "Access-Control-Allow-Origin",
        }),
    )

    wrapperTest := func(w http.ResponseWriter, r *http.Request) {
        handler := corsMiddleware(http.HandlerFunc(handleTest))
        handler.ServeHTTP(w, r)
    }

    http.HandleFunc("GET /test", wrapperTest)
    http.HandleFunc("POST /test", wrapperTest)

    port := cmp.Or(os.Getenv("PORT"), "3030")

    log.Fatal(http.ListenAndServe((":" + port), nil))
}

func handleTest(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, world!"))
}

1249416459868966956


2 years ago

perhaps you have something missconfigured with cloudflare? either way, this would not be an issue with Railway


Welcome!

Sign in to your Railway account to join the conversation.

Loading...