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