1

I am trying to make a Post request using frontend React to my backend in Golang like this:

const Posttobackend = async (values) => {
    try {
        const response = await fetch(`${API_URL}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(values),
            mode: 'cors',
        });
        if (response.ok) {
            const data = await response.json();
            return data;
        } else {
            const errorData = await response.json();
            throw new Error(`Error: ${errorData.message || 'An error occurred while processing your reservation. Please try again.'}`);
        }
    } catch (error) {
        console.error("Error: ", error);
        throw error;
    }
}; 

but i get this error: Access to fetch at 'https://abcde.eu.ngrok.io' from origin 'https://webpage.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. "strict-origin-when-cross-origin" The backend is written in Golang and I actually use the gin cors middleware and i receive a


[GIN] 2023/06/04 - 21:44:47 | 204 |            0s | 2003:dc:bf4a:4f00:9c3e:9c3b:b711:797 | OPTIONS  "Posttobackend"

The Go code is this:


package main

import (
    "net/http"
    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)
func main() {
    // Setup the Gin server.
    router := gin.Default()

    // Add CORS middleware
    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"*"} // ive tried pointing to the exact website, thus https://webpage.com, but it didnt help
    config.AllowMethods = []string{"GET", "POST", "OPTIONS", "PUT", "DELETE"}
    config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Accept", "Authorization"} // tried *, but didnt help

    router.Use(cors.New(config))
    // API routes.
    api := router.Group("/")
    {
        api.POST("Posttobackend", posttobackend)

    }

    // Start the server.
    router.Run(":8080")
}

I am using ngronk since i am making this request from a digitalocean droplet and ive created a widget from the react and im using it inside script frame on a website. In other questions ive read that using 'no cors' as option would help, but then i wont be able to read the server's response. On ngrok i get this response wit 204 no content

Access-Control-Allow-Headers    *
Access-Control-Allow-Methods    GET,POST,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin *
Access-Control-Max-Age  43200
Date    Sun, 04 Jun 2023 19:44:47 GMT

When i use chrome.exe --disable-web-security --user-data-dir="C:/ChromeDevSession", thus without cors, the request reaches the server without any problems.

Thank you very much for your help.

Best regards

  • 1
    in headers add the `"*/*"`, and if you want to print the exact website if it's not the default port make sure you add the port too like `https://myReactApp.com:9000` and the protocol if you are using a protocol – Isaac Weingarten Jun 05 '23 at 00:13
  • thank you, it is running on the default port and ive added in the headers the */* `const response = await fetch(`${API_URL}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': '*/*', }, body: JSON.stringify(values), mode: 'cors', }); ` But i still receive the same error – LupefiascoMosdef Jun 05 '23 at 08:28
  • ngrok was the problem, ive tried to tunnel it via Packetriot and the error didnt come up again. anyways thank you for your help, but if you like you can take the credits for solving it, just answer the question below :) – LupefiascoMosdef Jun 05 '23 at 11:26
  • 1
    you need to add to your go-server `config.AllowHeaders = "[*/*","custom/headers",...]`. in your JS won't help if you add there any headers, cors is something that needs to be configured on your server the browser makes a header request and the server needs to respond with a 200. you didn't set up gin cors the Correct way, in gin, the cors needs to be set in a middleware look at this question's answers https://stackoverflow.com/questions/29418478/go-gin-framework-cors. if you use a proxy server like ngrok, or NGINX that should take care of the cors, not gin – Isaac Weingarten Jun 12 '23 at 04:54

1 Answers1

0

try to send in request headers like below

  const headers = {
        'Authorization':`Bearer ${secretToken}`,
        'ngrok-skip-browser-warning': 'any'
    };

and on servervside add (I am using django-cors-headers middleware so)

CORS_ALLOW_HEADERS = (
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
    "ngrok-skip-browser-warning"
)