1

I try to fetch some session data using a svelte frontend and i get a response status 401

This is the code that i use for the cors

router.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"http://localhost:5173"}, // Your frontend URL
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
        AllowHeaders:     []string{"Origin", "Content-Type"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
    }))

and this is the code that i use for the session

    store := cookie.NewStore([]byte(conf.Session.Key))
    store.Options(sessions.Options{
        Path:     "/",
        MaxAge:   3600 * 24,
        Secure:   false,
        HttpOnly: true,
        SameSite: http.SameSiteLaxMode,
    })

and this is the code that make the request for that data

    import { onMount } from 'svelte';
    import { goto } from '$app/navigation';

    async function check() {
        try {
            const response = await fetch('http://localhost:8080/check');
            if(response.ok) {
                const result = await response.json();
                if (result.message === "You are logged in!") {
                    goto('/dashboard');
                } else {
                    console.log('No connection')
                }
            }
        } catch (error){
            console.error('Error', error)
        }
    }

    onMount(() => {
        check();
    });
2
  • 1
    401 is not a CORS problem. The web browser is responsible for enforcing the Same-Origin Policy, and if the response from the server doesn't contain CORS headers that relaxes the Same-Origin Policy, then the web browser will reject the fetch() promise. So if your client-side JS manages to read out the status code 401, then you don't have any CORS problems, and the problem is that the server refused to carry out the request, for example because you didn't pass along any needed authorization information in the request.
    – Peppe L-G
    Commented Jun 4 at 10:31
  • In addition to @PeppeL-G's comment, note that neither allowing request header Origin nor exposing response header Content-Length is ever needed.
    – jub0bs
    Commented Jun 29 at 14:23

0

Browse other questions tagged or ask your own question.