CORS Problems with Flutter Web and Go Backend

I am experiencing difficulties with CORS while trying to connect my Flutter web application to a Go backend. I’ve configured the Go backend to allow all origins, yet I continue to face CORS-related issues in Flutter web. Could my version of Go be a factor in these problems, or is the issue within the Flutter web implementation? Here’s the code I’ve used in Go:

func main() {
    db, err := ConnectToDatabase()
    if err != nil {
        panic("Database connection failed")
    }
    InitializeTables(db)
    if err := PopulateCurrencies(db.DB); err != nil {
        panic("Currency seeding failed")
    }

    config := cors.Options{
        AllowedOrigins: []string{"https://app.mam-laka.com", "*mam-laka.com", "*"},
        AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
        AllowedHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "Access-Control-Allow-Origin"},
        ExposedHeaders:   []string{"Content-Length"},
        AllowCredentials: true,
        MaxAge:          12 * time.Hour,
    }
    router := InitializeRouter(db)
    router.Use(cors.New(config))
    router.Run(":8091")
}

In Flutter, I have the following async function for signing in:

Future<void> loginUser() async {
    Map<String, dynamic> requestData = {
        "email": emailController.text,
        "password": passwordController.text,
    };

    try {
        setState(() {
            isLoading = true;
        });

        Map<String, String> requestHeaders = {
            "Content-Type": "application/json",
        };

        var loginUrl = Uri.parse('$baseApiUrl/login');
        var serverResponse = await http.post(loginUrl, headers: requestHeaders, body: jsonEncode(requestData));
        Map responseBody = jsonDecode(serverResponse.body);
        print(responseBody);

        if (serverResponse.statusCode == 200 && responseBody["message"] == "Login successful") {
            var secureBox = await Hive.box('userBox');
            secureBox.put('authToken', responseBody['token']);
            secureBox.put('fullName', '${responseBody['user']['firstName']} ${responseBody['user']['lastName']}');
            secureBox.put('userEmail', responseBody['user']['email']);
            print(secureBox.get("userEmail"));
            print(secureBox.get("fullName"));

            Navigator.push(
                context,
                PageTransition(
                    type: PageTransitionType.rightToLeft,
                    child: MainNavigation(),
                ),
            );
            displaySnackBar(
                Overlay.of(context),
                CustomSnackBar.success(message: responseBody["message"]),
            );
        } else if (serverResponse.statusCode == 401) {
            displaySnackBar(
                Overlay.of(context),
                CustomSnackBar.error(message: "Incorrect credentials. Please retry."),
            );
        } else {
            displaySnackBar(
                Overlay.of(context),
                CustomSnackBar.error(message: responseBody["message"] ?? "An unexpected error occurred, please retry."),
            );
        }
    } catch (error) {
        print("Error: $error");
        displaySnackBar(
            Overlay.of(context),
            const CustomSnackBar.error(message: "Please check your internet connection."),
        );
    } finally {
        setState(() {
            isLoading = false;
        });
    }
}

sometimes go’s gorilla/cors package can need specific setup! instead of using: ‘*mam-laka.com’, try everything with ‘https://’ and double-check if flutter’s running on https locally. i’ve encountered similar probs where the protocol mismatch was the real issue. just another angle to investigate!

CORS issues could be tricky! Make sure your browser cache isn’t storing old policies. Also, double-check if there are any browser extensions that might block CORS. Lastly, verify your Go server’s handlers cover all routes you are accessing from Flutter, not just ‘login’. Hope it helps!

Hey ClimbingMonkey, have you tried checking if the ‘*’ in AllowedOrigins conflicts with specific origins? Also, flutter doesn’t always show CORS errors clearly. Consider running a curl request from the terminal to see if headers are sent as expected. What other headers or types of calls does your app make?

In your Flutter web environment, consider adding a proxy configuration during development. This can bypass CORS by redirecting your API calls through a server that doesn’t impose CORS restrictions, which could help identify whether the issue is with your backend configuration or within the Flutter web application itself. Additionally, verify that your Go backend is responding to OPTIONS requests, which are often used by browsers as preflight checks when making cross-origin requests.

Hey ClimbingMonkey! Is there a chance the CORS issue might be related to the way headers are structured or handled? Have you tried logging the request headers on the server to see what’s being sent over? :face_with_monocle: Also, when you adjusted the headers, did you restart the Go server to ensure changes took effect? :thinking: