【发布时间】:2021-05-29 13:11:01
【问题描述】:
我在 Ionic/Angular 应用程序中使用 AngularFire。
我正在尝试调用一个函数:
const getDiretions = this.functions.httpsCallable('getDirections');
const result = await getDiretions({
lat1: lastStop.coordinates.latitude,
lng1: lastStop.coordinates.longitude,
lat2: step.coordinates.latitude,
lng2: step.coordinates.longitude,
}).toPromise();
但我明白了:
Access to fetch at 'https://europe-west6-xxxxxx-yyyyyy.cloudfunctions.net/getDirections' from origin 'http://localhost:8100' 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.
从 localhost 使这个请求成功的正确方法是什么?
编辑
对不起,这是我初始化this.functions的方法:
constructor(private functions: AngularFireFunctions) {}
编辑 2
这里是后端定义:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
export const getDirections = functions.region('europe-west6').https.onRequest((request, response) => {
const lat1: number = +(request.query.lat1 ?? '0');
const lng1: number = +(request.query.lng1 ?? '0');
const lat2: number = +(request.query.lat2 ?? '0');
const lng2: number = +(request.query.lng2 ?? '0');
//Do something with lat/lng
response.status(200);
response.send(answer);
});
【问题讨论】:
-
您能否展示您如何在前端通过 Firebase 初始化 Cloud Functions(即如何定义
this.functions)以及如何定义函数在索引中的位置.js?我尝试检查您是否在初始化时设置了适当的值。因为您似乎调用了在默认us-central1位置以外的位置运行的函数。另请注意,您不需要调用toPromise(),HttpsCallable 已经返回了一个 Promise。 -
@RenaudTarnec 我添加了一些细节。关于位置,我刚刚在我的 app.module.ts 中添加了
{ provide: REGION, useValue: 'europe-west6' },。我没有做任何其他事情来设置角火的功能。 VS Code 告诉我 httpsCallable 正在返回一个 Observable。 -
您能否说明您如何在
index.ts或index.js文件(即在后端)中定义云函数? -
"VS Code 告诉我 httpsCallable 正在返回一个 Observable。" => angularfire 可以将其封装在 Observable 中。我不能在这方面多说,我不精通 angularfire... :-)
-
@RenaudTarnec 我添加了如何在后端声明函数的问题。你知道发生了什么吗?
标签: angular firebase google-cloud-functions cors angularfire