reactjsgogo-fiber

CORS error for golang fiber with React front-end


I am using golang fiber server, setup like this:

package main

import (
    "go-auth/database"
    "go-auth/routes"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
    database.Connect()
    app := fiber.New()

    routes.Setup(app)

    app.Use(cors.New(cors.Config{
        AllowHeaders:     "Origin, Content-Type, Accept, Content-Length, Accept-Language, Accept-Encoding, Connection, Access-Control-Allow-Origin",
        AllowOrigins:     "*",
        AllowCredentials: true,
        AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
    }))
    app.Listen(":3800")
}

I am calling it via React fetch:

    const response = await fetch('http://127.0.0.1:3800/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name,
            email,
            password
        })
    }).then(response => response.json());
    console.log(response);

Am I doing something wrong? CORS is disabled on the server side already. Here is the error I get:

Access to fetch at 'http://127.0.0.1:3800/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Also this error:

register.js:17          POST http://127.0.0.1:3800/api/register net::ERR_FAILED

Solution

  • Found the error, hope it help someone else, literally jusst need to move routes.Setup(app) to AFTER setting CORS up, which makes sense I guess 🤦‍♂️🤦‍♂️:

    func main() {
        database.Connect()
        app := fiber.New()
    
        app.Use(cors.New(cors.Config{
            AllowHeaders:     "Origin,Content-Type,Accept,Content-Length,Accept-Language,Accept-Encoding,Connection,Access-Control-Allow-Origin",
            AllowOrigins:     "*",
            AllowCredentials: true,
            AllowMethods:     "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
        }))
        routes.Setup(app)
        app.Listen(":3800")
    }