Next.js Discord

Discord Forum

Serverless Golang React Cors Error

Answered
Yacare Caiman posted this in #help-forum
Open in Discord
Yacare CaimanOP
I am getting cors error I do not know why because I am doing GET. I followed the Guide for cors, it does not work for now this is what I have.

func enableCors(w *http.ResponseWriter) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PATCH, DELETE, PUT")
    (*w).Header().Set("Access-Control-Allow-Headers", "Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, Access-Control-Expose-Headers, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version")
    (*w).Header().Set("Access-Control-Allow-Credentials", "true")
}

func Handler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "OPTIONS" {
        enableCors(&w)
        w.WriteHeader(http.StatusOK)
        return
    }

    userIP := r.RemoteAddr

    enableCors(&w)

    webhookURL := "mywebhook"

    payload := map[string]interface{}{
        "color":     0x31b4f5,
        "content":   fmt.Sprintf("**Client IP**: %s", userIP),
        "timestamp": time.Now().Format("2006-01-02 15:04:05"),
    }

    jsonPayload, err := json.Marshal(payload)

    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte("Internal Server Error"))
        return
    }

    resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonPayload))
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte("Internal Server Error"))
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode >= 200 && resp.StatusCode < 300 {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("Webhook sent successfully"))
    } else {
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte("Internal Server Error"))
    }
}
Answered by Yacare Caiman
Fixed it, idk how I deleted my func on vercel and reupload.
View full answer

6 Replies

Yacare CaimanOP
In my frontend, I call it that way:

useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(process.env.REACT_APP_LOGGER);

      if (response.ok) {
        localStorage.setItem('visited', 'true');
      }
    };

    fetchData();
  }, []);


The error I get is:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://v1-1ikazll41-imzolofts-projects.vercel.app/api/ipLogger. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Website error can be viewed here: https://imzoloft.xyz
Yacare CaimanOP
I also have in vercel.json routes array that accept every http type fo request
Yacare CaimanOP
{
  "functions": {
    "api/ipLogger.go": {
      "maxDuration": 10
    }
  },
  "routes": [
    {
      "src": "/api/(.*)",
      "status": 200,
      "methods": ["POST", "OPTIONS", "GET", "PATCH", "DELETE", "PUT"],
      "headers": {
        "Access-Control-Allow-Headers": "Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, Access-Control-Expose-Headers, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,DELETE,PATCH,POST,PUT"
      }
    }
  ]
}
Yacare CaimanOP
Fixed it, idk how I deleted my func on vercel and reupload.
Answer
yeah, I don't see any issue from the code you provided