Error calling my api from frontend

Expected to work without errors, but getting these following errors in the console:

Checking session... [script.js:125:13](https://it-club-3qbsuaqhv-ahmad-zarirs-projects.vercel.app/static/js/script.js)

Cookie “_vercel_sso_nonce” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”. 2 [check_session](https://it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app/check_session)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app/check_session. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.

Error checking session: TypeError: NetworkError when attempting to fetch resource. [script.js:147:17](https://it-club-3qbsuaqhv-ahmad-zarirs-projects.vercel.app/static/js/script.js)

XHROPTIONShttps://it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app/loginCORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app/login. (Reason: CORS request did not succeed). Status code: (null).

code for my static/js:

const IP = 'it-club-nhglwo0kg-ahmad-zarirs-projects.vercel.app';
document.addEventListener("DOMContentLoaded", () => {
    initializePage();
});

// Initialize the page elements and event listeners
function initializePage() {
    const showPasswordCheckbox = document.getElementById("show-password");
    const emailField = document.getElementById("email");  // Changed from "username" to "email"
    const passwordField = document.getElementById("password");

    // Ensure the password checkbox is unchecked by default
    showPasswordCheckbox.checked = false;

    // Toggle password visibility
    showPasswordCheckbox.addEventListener("change", () => {
        passwordField.type = showPasswordCheckbox.checked ? "text" : "password";
    });

    // Handle Enter key in the email field
    emailField.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            passwordField.focus();
        }
    });

    // Handle Enter key in the password field
    passwordField.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            login();
        }
    });

    // Check for an active session when the page loads
    checkSession();
}

// Display the loading screen
function showLoading() {
    const loadingScreen = document.getElementById("loading-screen");
    if (loadingScreen) {
        loadingScreen.style.display = "flex";
    }
}

// Hide the loading screen
function hideLoading() {
    const loadingScreen = document.getElementById("loading-screen");
    if (loadingScreen) {
        loadingScreen.style.display = "none";
    }
}

// Handle user login
async function login() {
    const email = document.getElementById("email").value;  // Changed from "username" to "email"
    const password = document.getElementById("password").value;
    const message = document.getElementById("message");

    if (!email || !password) {
        displayMessage("Please fill in all fields", "red");
        return;
    }

    showLoading();

    try {
        const response = await fetch(`http://${IP}/login`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email, password }),  // Send email instead of username
            credentials: "include",
        });

        if (!response.ok) {
            throw new Error("Failed to authenticate");
        }

        const result = await response.json();

        if (result.success) {
            await loadUserPage(result.user);
            displayMessage("Login successful!", "green");
        } else {
            displayMessage("Invalid email or password", "red");
        }
    } catch (error) {
        displayMessage("An error occurred. Please try again later", "red");
    } finally {
        hideLoading();
    }
}

async function loadUserPage(user) {
    console.log("Loading user page for:", user);
    showLoading();

    try {
        const response = await fetch(`http://${IP}/user_page`, {
            method: "GET",
            credentials: "include",
        });

        if (!response.ok) {
            console.error("Failed to load user page", response);
            throw new Error("Failed to load user page");
        }

        const pageContent = await response.text();
        document.body.innerHTML = pageContent;  // Replace body content with user page

        // Ensure user data is inserted after content is loaded
        console.log("Populating user data into the page...");
        document.getElementById("user-name").textContent = user.name;
        document.getElementById("user-id").textContent = user.id;
    } catch (error) {
        console.error("Error loading user page:", error);
    } finally {
        hideLoading();
    }
}

async function checkSession() {
    console.log("Checking session...");  // Add logging here
    showLoading();

    try {
        const response = await fetch(`http://${IP}/check_session`, {
            method: "GET",
            credentials: "include",
        });

        const result = await response.json();
        console.log("Session check result:", result);  // Log the session check result

        if (result.success) {
            console.log("Session active, loading user page...");
            // If session is active, load the user page
            await loadUserPage(result.user);
        } else {
            console.warn("No active session. Displaying login page.");
            displayMessage("Please log in.", "red");
            hideLoading();
        }
    } catch (error) {
        console.error("Error checking session:", error);
    } finally {
        hideLoading();
    }
}

// Log out the user and clear session data
async function logout() {
    showLoading();

    try {
        await fetch(`http://${IP}logout`, {
            method: "POST",
            credentials: "include",
        });
        localStorage.removeItem("user");
        location.reload();
    } catch (error) {
        console.error("Error logging out:", error);
    } finally {
        hideLoading();
    }
}

// Display a message to the user
function displayMessage(text, color) {
    const message = document.getElementById("message");
    if (message) {
        message.style.color = color;
        message.textContent = text;
    }
}

https://it-club-3qbsuaqhv-ahmad-zarirs-projects.vercel.app/

The domain troubleshooting guide can help with most custom domain configuration issues. You might be able to use that guide to solve it before a human is available to help you. Then you can come back here and share the answer for bonus points.

You can also use v0 to narrow down the possibilities.

Hi @zarirdev, welcome to the Vercel Community!

I see you are facing some CORS issues. Can you share a project overview: folder structure, API purpose, what is it that you’re trying to build, and where is the API deployed?

This will help us understand what the code is expected to do and why is it failing.

From the looks of it, one thing I’d recommend is using https for all Vercel deployed URLs and ensure that the string interpolation is correct. For example,

 await fetch(`http://${IP}logout`, {
            method: "POST",
            credentials: "include",
        });

should be:

 await fetch(`https://${IP}/logout`, {
            method: "POST",
            credentials: "include",
        });

Yes that was one of the issues, the main issue was i didn’t write CORS(app, supports_credentials=True). But anyway it has been fixed.
But i am facing a new issue which is the domain is not updating with the new code, the “assigned domain”. But the website works completely as expected using the it-club-git-main-ahmad-zarirs-projects.vercel.app. Anyways, thanks.

1 Like

Hi @zarirdev, thanks for sharing the solution here.

Feel free to ask more questions here.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.