奇怪的 Firebase 身份验证/端点响应问题

问题描述 投票:0回答:1

我是一名业余程序员,所以绝对是初学者水平。

我正在 Firebase 上开发一个 node.js 应用程序,它需要用户创建或加入一个组。我在前端有两个方法,每个方法调用不同的端点。

joinGroup()
工作没有任何问题。

createNewGroup()
但是,有奇怪的问题:

  1. 用户身份验证后第一次尝试时,会在 Firestore 中成功创建新组,但是,在
    .then(response => {
  2. 之后不会处理响应
  3. 在后续尝试中,无法在
    fetchWithAuth
  4. 中获得 Firebase 身份验证令牌

感谢大家帮助解决这个问题!

前端:

function createNewGroup() {
    console.log("Attempting to create group...");
    const groupId = document.getElementById('group').value;
    fetchWithAuth(`${endpointBaseUrl}/create-new-group`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ groupId })
    })
    .then(response => {
        console.log("Received response from fetch request inside createNewGroup");
        console.log(response);
        if (response.success) {
            console.log("Successfully created group:", response.groupId);
        } else {
            console.error('Failed to create group:', response.message);
            throw new Error('Failed to join group: ' + response.message);
        }
    })
    .catch(error => {
        console.error('Error creating new group:', error);
    });
}

function joinGroup() {
    const groupId = document.getElementById('group').value;
    if (!groupId) {
        console.error('Group ID is required');
        document.getElementById('response').textContent = 'Please enter a group ID.';
        return;
    }

    console.log('Joining group with ID:', groupId);
    fetchWithAuth(`${endpointBaseUrl}/join-group`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ groupId })
    })
    .then(response => {
        console.log("Received response from fetch request inside joinGroup");
        console.log(response);
        if (response.success) {
            console.log("Successfully joined group:", response.groupId);
            document.getElementById('response').textContent = "Successfully joined group: " + response.message;
        } else {
            console.error('Failed to join group:', response.message);
            document.getElementById('response').textContent = "Error joining group: " + response.message;
            throw new Error('Failed to join group: ' + response.message);
        }
    })
    .catch(error => {
        console.error('Error joining group:', error);
        document.getElementById('response').textContent = 'Error joining group: ' + error.message;
    });
}

// Helper function to perform fetch requests with Firebase authentication
function fetchWithAuth(url, options = {}) {
    console.log("Starting fetchWithAuth for URL:", url);
    console.log("Starting fetchWithAuth with options:", options);

    if (!firebase.auth().currentUser) {
        console.error('No authenticated user.');
        return Promise.reject(new Error('No authenticated user.'));
    }

    // Ensure headers are initialized in options to avoid undefined issues
    if (!options.headers) {
        console.log("Headers are empty");
        options.headers = {};
    }

    return firebase.auth().currentUser.getIdToken(true)
    .then(token => {
        console.log("Obtained Firebase ID token.");

        // Safely append the Authorization header to the existing headers
        options.headers['Authorization'] = `Bearer ${token}`;

        console.log("Headers set for request:", options.headers);

        // Perform the fetch inside the then block to ensure headers are set after token retrieval
        return fetch(url, options);
    })
    .then(response => {
        console.log("Received response from fetch request.");

        if (!response.ok) {
            console.error('Network response was not ok:', response);
            throw new Error('Network response was not ok');
        }

        return response.json();
    })
    .then(data => {
        console.log("Parsed JSON data from response:", data);
        return data;
    })
    .catch(error => {
        console.error('Fetching with auth failed:', error);
        throw error;
    });
}

后端:

// Endpoint to create a new group
app.post("/create-new-group", authenticate, async (req, res) => {
    const newGroupId = generateRandomGroupId();
    console.log("Backend attempting to create group with ID:", newGroupId);
    try {
        await admin.firestore().collection('groups').doc(newGroupId).set({
            members: [req.user.uid]
        });
        res.json({ success: true, groupId: newGroupId, message: "Created group successfully" });
        console.log("Backend created group with ID:", newGroupId);
    } catch (error) {
        console.error("Error creating new group:", error);
        console.log("Backend error when attempting to create group with ID:", newGroupId);
    }
});

// Endpoint to join an existing group
app.post("/join-group", authenticate, async (req, res) => {
    const { groupId } = req.body;
    console.log("Backend attempting to join group with ID:", groupId);
    const groupRef = admin.firestore().collection('groups').doc(groupId);
    try {
        const groupDoc = await groupRef.get();
        if (groupDoc.exists) {
            const members = groupDoc.data().members;
            members.push(req.user.uid);
            await groupRef.update({ members });
            res.json({ success: true, groupId: groupId, message: "Joined group successfully" });
        } else {
            res.status(404).json({ message: "Group not found" });
        }
    } catch (error) {
        console.error("Error joining group:", error);
        res.status(500).json({ success: false, message: "Internal server error" });
    }
});
javascript node.js firebase google-cloud-firestore
1个回答
0
投票

这就是问题所在:

在我的 html 中,我通过 onclick 调用 joinGroup(),但通过事件监听器调用 createNewGroup()。由于某种原因,这不起作用。当我通过 onclick 调用 createNewGroup() 时,一切正常。

<body>
    <h1>Setup your account</h1>
    <form id="roleForm">
        <div id="initialQuery">
            <p>Did your partner already create an account?</p>
            <button type="button" id="yesButton">Yes</button>
            <button type="button" id="noButton">No</button>
        </div>
        <div id="groupInput" style="display:none;">
            <label for="group">Enter your group ID:</label>
            <input type="text" id="group" name="group">
            <button type="button" onclick="joinGroup()">Join Group</button>
        </div>
        <div id="newGroupInfo" style="display:none;">
            <p>Your new group ID will be displayed here.</p>
            <input type="text" id="group" name="group">
            <button id="createGroupButton">Create New Group</button>
        </div>
        <div id="response"></div>
    </form>
</body>
const createGroupButton = document.getElementById('createGroupButton');
if (createGroupButton) {
    createGroupButton.addEventListener('click', createNewGroup);
} else {
    console.error('Create group button not found');
}
© www.soinside.com 2019 - 2024. All rights reserved.