我正在尝试创建一些 Firebase Cloud Functions 并使用本地测试它们
firebase emulators:start --only functions
这些函数应该使用 fetch 调用一些外部服务。
我发现在将函数部署到 Firebase 云时可以调用这些外部服务,但在模拟器中本地运行时无法调用它们:
import 'cross-fetch/polyfill';
export const fetchTest = functions
.region(config.firebaseRegion)
.https.onRequest((request: Request, response: Response) => {
fetch("https://www.wikipedia.org/", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
fetch("https://googleapis.com/foo", {
method: 'GET',
}).then(value => {
console.log("Fetched: ", value);
}).catch(reason => {
console.log("Fetch failed: ", reason);
});
response.send("Done");
});
这是我在模拟器中调用 fetchTest 时得到的输出:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
⚠ Google API requested!
- URL: "https://googleapis.com/foo"
- Be careful, this may be a production service.
查看源代码似乎在模拟器中实现了一些过滤:
https://github.com/firebase/firebase-tools/blob/0586ee1e23adc64b0fe8607a026ba472a6bd7d2e/src/emulator/functionsEmulatorRuntime.ts
if (href && !history[href]) {
history[href] = true;
if (href.indexOf("googleapis.com") !== -1) {
new EmulatorLog("SYSTEM", "googleapis-network-access", "", {
href,
module: bundle.name,
}).log();
} else {
new EmulatorLog("SYSTEM", "unidentified-network-access", "", {
href,
module: bundle.name,
}).log();
}
}
这种限制有什么理由吗?是否有解决方法?
谢谢!
最佳答案
当您看到“未知网络请求”这样的日志时:
⚠ Unknown network resource requested!
- URL: "https://www.wikipedia.org/"
它们只是警告。允许实际请求通过。该日志旨在告诉您模拟器正在访问您机器之外的资源。这通常是人们想要避免的事情,因为本地测试是封闭的,但有时这就是您想要做的,您可以安全地忽略警告!
关于firebase - 无法使用 fetch() 从 Firebase 模拟器访问 googleapis.com 以外的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57030960/