【发布时间】:2022-02-12 16:08:35
【问题描述】:
我在调整我正在处理的 Firebase 云功能的代码(使用 cors)时遇到问题。
下面是函数的代码:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";
import { on } from "events"
const corsHandler = cors({origin: true});
admin.initializeApp();
exports.myFunc = functions.https.onRequest(function(req, resp) {
corsHandler(req, resp, async () => {
if (req.query.from !== undefined) {
const from = String(req.query.from);
functions.logger.log("From (URL):", from);
} else {
functions.logger.log("req.query.from is undefined");
}
const from = req.body.from;
functions.logger.log("Hello from --myFunc--");
admin.auth().getUserByEmail(from)
.then(function(userRecord) {
console.log("Successfully fetched user data:", userRecord.toJSON());
})
.catch(function(error) {
console.log("Error fetching user data:", error);
});
}); // End corsHandler.
});
当我在浏览器中使用这个 URL 调用这个函数时:
https://us-central1-myapp.cloudfunctions.net/myFunc?from=example@example.com
我在日志中得到了我所期望的,即:
myFunc: From (URL): example@example.com
另一方面,当我从网络应用程序中使用此 Ajax 代码调用函数时:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send("from=example@example.com");
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log('THE DATA:',data);
};
我有一个问题,在 Web 控制台日志中得到以下信息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.
我一定错过了什么。谁能指出它是什么?
【问题讨论】:
-
您能否将
corsHandler更改为cors看看是否能解决问题?如果这没有帮助,您可以尝试this answer 中提到的,这也在this document 中指定吗? -
你想在哪一行将 corsHandler 改为 cors. corsHandler 出现在代码中的 2 个位置,并且 cors 已被使用。我做了一个快速试验,但只得到错误。我需要说我实际上并不明白它如何产生任何影响。但如果你有一个好主意,我当然愿意尝试。
-
@Prabir。我花了一些时间来尝试您评论的第二部分(按照您提到的答案并阅读文档),但我仍然收到与以前相同的错误消息。而且更多的执行甚至没有到达函数内部。 https.onRequest(function(req,resp) {...} 块。所以没有机会使用添加的代码(即 resp.set("Access -Control-Allow-Origin", "*"); ... 等等 ....)。
-
你能告诉你你是怎么知道执行没有到达功能块内部的吗?你有任何错误吗?如果块内的代码没有被执行,那么你的函数代码似乎有问题。
-
@Prabir。我得出这个结论是因为我在代码中输入的消息没有出现在日志中。但经过更多的试验后,我取得了一些进展并解决了这个问题。
标签: node.js firebase google-cloud-functions firebase-hosting