You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地运行Firebase模拟器时出现Fastify CORS错误求助

本地使用Fastify+Firebase模拟器时的CORS错误问题

错误详情

signin:1 Access to fetch at 'http://127.0.0.1:5001/<redacted>/asia-southeast1/hello/api/v1/session_login' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Fastify后端代码

server.register(cors, {
    origin: true,
    methods: ["GET", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
    credentials: true,
});

server.register(singleClientAndContact, { prefix: API_V1 });

exports.hello = onRequest(
    {
        secrets: [DB_USER, DB_PASSWORD],
        cors: true,
        region: "asia-southeast1",
    },

    async (req, res) => {
        await server.ready();
        server.server.emit("request", req, res);
    }
);

React前端代码

登录处理逻辑

const handleGoogle = async () => {
    const userCredential = await signInWithEmailAndPassword(
        auth,
        username,
        password
    );

    const idToken = await getIdToken(userCredential.user);
    const res = await postIdTokenToSessionLogin(idToken);

    setUsername("");
    setPassword("");

    if (res.ok) {
        return navigate("/client_management", { replace: true });
    }
};

请求会话登录的函数

async function postIdTokenToSessionLogin(idToken: string) {
    return await fetch(`${DOMAIN}/api/v1/session_login`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ idToken }),
        credentials: "include",
    });
}

firebase.json配置

{
  "functions": [
    {
      "source": "backend",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log",
        "*.local"
      ],
      "predeploy": [
        "npm --prefix \"$RESOURCE_DIR\" run lint",
        "npm --prefix \"$RESOURCE_DIR\" run build"
      ]
    }
  ],
  "hosting": {
    "public": "frontend/dist",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

已尝试的操作

  • 将Firebase函数的Cloud Invoker权限设置为allUsers
  • 初始化Firebase并连接到模拟器:
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
const functions = getFunctions(getApp(), "asia-southeast1");
setPersistence(auth, browserLocalPersistence);
connectFunctionsEmulator(functions, "localhost", 5001);

问题说明

仅当设置credentials: "include"时才会出现该问题,不清楚遗漏了什么,恳请提供帮助。


内容的提问来源于stack exchange,提问作者cornstar94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:54:58