繁体   English   中英

Firebase 云 Function 返回错误访问被阻止从源 http://localhost:3000

[英]Firebase Cloud Function Returns Error Access Blocked From origin http://localhost:3000

我有一个 firebase function。 我从我的应用程序发出请求调用,如下所示:

 getNonce = async () => {
    var requestOptions = {
      method: "POST",
      headers: {
        "Content-Type": "Application/JSON",
      },
      body: JSON.stringify({ address: this.state.provider.selectedAddress }),
      maxAge: 3600,
      //   mode: "no-cors",
    };
    const fetchURL = `https://XXXX-XXXX-XXXX.cloudfunctions.net/getNonceToSign`;
    const response = await fetch(fetchURL, requestOptions)
      .then((data) => data.json())
      .then((body) => {
        console.log(body);
      });
  };

我的云 function 如下所示:

import * as functions from "firebase-functions";
import * as firebaseAdmin from "firebase-admin";
import * as corsLib from "cors";
import {recoverPersonalSignature} from "@metamask/eth-sig-util";

const admin = firebaseAdmin.initializeApp();

const cors = corsLib({
    origin: "localhost:3000",
});


export const getNonceToSign = functions.https.onRequest((request, response) =>
    cors(request, response, async () => {
        response.set("Access-Control-Allow-Origin", "http://localhost:3000");
        response.set("Access-Control-Allow-Headers", "*");
        try {
            if (request.method !== "POST") {
                return response.sendStatus(403);
            }
        
        // some more implementation

        } catch (err) {
            console.log(err);
            return response.sendStatus(500);
        }
    })
);      

我在一些帖子上读到这可能是一个起源问题。 因此,我在 corsLib 初始化期间以及通过设置Access-Control-Allow-OriginAccess-Control-Allow-Headers在我的请求中包含了localhost:3000 不幸的是,响应是相同的错误:

Access to fetch at 'https://XXXX-XXXX-XXXX.cloudfunctions.net/getNonceToSign' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

还有什么我可以尝试的吗? 在 cors 初始化和云内响应期间添加 localhost 是迄今为止我发现的唯一解决方案,但它们不起作用。

最后,如果我设置“no-cors”,则从服务器返回ERROR 403 我不知道为什么,因为请求方法是POST所以理论上它不应该返回 403。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM