中间件,但 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 问题
发布评论