Go Fiber framework gives Cors error even if the setup is done correctly

332 Views Asked by At

I use fiber for my api app written in golang. When I use

  • Postman, everything works fine
  • Web Browser, again it works
  • But from the frontend application written in Nextjs, it gives Cors Error,

127.0.0.1:8080/tasks:1 Failed to load resource: net::ERR_FAILED localhost/:1 Access to XMLHttpRequest at 'http://127.0.0.1:8080/tasks' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I set up my fiber app as below. But no success,

    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:     "*",
        AllowOriginsFunc: nil,
        AllowCredentials: false,
        AllowMethods: strings.Join([]string{
            fiber.MethodGet,
            fiber.MethodPost,
            fiber.MethodHead,
            fiber.MethodPut,
            fiber.MethodDelete,
            fiber.MethodPatch,
        }, ","),
        MaxAge: 3600,
    }))

It is appriciated if anyone can help

I also tried default cors setup like

app := fiber.New()
app.Use(cors.New())

My frontend code is given below,

"use client";

import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import { getTodoList } from "./api/todos";
import axios from "axios";

const queryClient = new QueryClient({});

export default function Home() {
  return (
    <QueryClientProvider client={queryClient}>
      <main className='flex min-h-screen flex-col items-center justify-between p-24'>
        <div className='z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex'>
          <h1>Home Page</h1>
          <ul>
            <Example />
          </ul>
        </div>
      </main>
    </QueryClientProvider>
  );
}

function Example() {
  interface Todo {
    id: number;
    title: string;
    description: string;
    is_completed: boolean;
  }

  const { isLoading, error, data, isFetching } = useQuery({
    queryKey: ["repoData"],
    queryFn: () =>
      axios.get("http://127.0.0.1:8080/tasks").then((res) => res.data),
  });

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return (
    <div>
      <h1>{data}</h1>
      <div>{isFetching ? "Updating..." : ""}</div>
    </div>
  );
}

1

There are 1 best solutions below

0
Alibaba Dev On

I solved my own issue. Simply deleted the Axios header configuration in my API . So the reason for the problem was not related to Go Fiber.

Just deleted unnecessary "headers" code in axios instance below.

const BASE_URL = "http://127.0.0.1:8080";

const apiClient = axios.create({
  baseURL: BASE_URL,
  headers: {
    ...
  }
});