尽管有 CORS 中间件,但 Firebase 云功能的 CORS 问题

编程入门 行业动态 更新时间:2024-10-04 19:23:50

尽管有 CORS <a href=https://www.elefans.com/category/jswz/34/1771157.html style=中间件,但 Firebase 云功能的 CORS 问题"/>

尽管有 CORS 中间件,但 Firebase 云功能的 CORS 问题

我在部署 Firebase Cloud Function 时遇到了 CORS 问题。我已经设置了 CORS 中间件,但在尝试向函数发出请求时仍然收到 CORS 错误。这是我的云功能的代码:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import cors from 'cors';

admin.initializeApp();

// Initialize cors middleware
const corsHandler = cors({ origin: true });

export const getSecretData = functions.https.onRequest((request, response) => {
  // Run the cors middleware
  corsHandler(request, response, async (err: Error | null) => {
    if(err) {
      response.status(500).send('CORS failed: ' + err.message);
      return;
    }

    // Verify the user's token
    if (!request.headers.authorization || !request.headers.authorization.startsWith('Bearer ')) {
      response.status(403).send('Unauthorized');
      return;
    }

    let idToken: string;
    if (request.headers.authorization && request.headers.authorization.startsWith('Bearer ')) {
      idToken = request.headers.authorization.split('Bearer ')[1];
    } else {
      response.status(403).send('Unauthorized');
      return;
    }

    try {
      const decodedIdToken = await admin.auth().verifyIdToken(idToken);
      console.log('ID Token correctly decoded', decodedIdToken);
    } catch (error) {
      console.error('Error while verifying Firebase ID token:', error);
      response.status(403).send('Unauthorized');
      return;
    }

    // Fetch secret data
    const secretData = {
      key: "value",
      anotherKey: "my secret",

尽管为每个请求设置并运行了 CORS 中间件,但我仍然收到 CORS 错误。即使我向 CORS 中间件添加错误处理以在 CORS 处理失败时以详细的错误消息响应,错误仍然存在:

OPTIONS

CORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS request did not succeed). Status code: (null).

这是我的应用程序代码:

import React, { useState, useEffect } from 'react';
import { signInWithMoralis as signInWithMoralisByEvm } from '@moralisweb3/client-firebase-evm-auth';
import { signInWithMoralis as signInWithMoralisBySolana } from '@moralisweb3/client-firebase-sol-auth';
import { httpsCallable } from 'firebase/functions';
import { User } from 'firebase/auth';
import { auth, functions, moralisAuth } from '../firebase'; // Make sure the path to your firebase config file is correct
import WalletConnectProvider from '@walletconnect/web3-provider';
import { Web3Provider } from '@ethersproject/providers';

function Login() {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    console.log("Firebase User: ", auth.currentUser);
    setCurrentUser(auth.currentUser);
  }, []);

  async function signInWithMetamask() {
    try {
      const result = await signInWithMoralisByEvm(moralisAuth);
      console.log("Moralis User: ", result.credentials.user);
      setCurrentUser(result.credentials.user);
    } catch (error) {
      console.log('Error signing in with MetaMask:', error);
    }
  }

  async function signInWithWalletConnect() {
    localStorage.removeItem('walletconnect');

    const provider = new WalletConnectProvider({
      rpc: {
        1: '',
      },
    });

    await provider.enable();

    const result = await signInWithMoralisByEvm(moralisAuth, {
      provider: new Web3Provider(provider),
    });

    setCurrentUser(result.credentials.user);
  }

  async function signInWithPhantom() {
    const result = await signInWithMoralisBySolana(moralisAuth);
    setCurrentUser(result.credentials.user);
  }

  async function signOut() {
    await auth.signOut();
    setCurrentUser(null);
  }

  async function getSecretData() {
    try {
      // Ensure there is a currently signed-in user
      if (!auth.currentUser) {
        throw new Error('No user currently signed in');
      }

      // Get the ID token of the currently signed-in user
      const idToken = await auth.currentUser.getIdToken();

      // Make an authenticated HTTP request to the getSecretData function
      const response = await fetch('', {
        headers: {
          'Authorization': `Bearer ${idToken}`
        }
      });

      if (!response.ok) {
        throw new Error('HTTP error ' + response.status);
      }

      const data = await response.json();
      alert(JSON.stringify(data));
    } catch (e) {
      console.log('Error getting secret data:', e);
      alert(e.message);
    }
  }

  return (
    <div className="App">
      <h1> 
          

更多推荐

尽管有 CORS 中间件,但 Firebase 云功能的 CORS 问题

本文发布于:2024-05-30 13:00:30,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   功能   CORS   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!