如何允许CORS与AngularFire函数在本地主机上开发



我在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.

让这个请求从本地主机成功的正确方法是什么?

编辑对不起,这是我如何初始化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);
});

你实际上是混合了HTTP云函数和可调用云函数。

你的Cloud Function代码对应一个HTTP代码(functions.region('europe-west6').https.onRequest(...)),但是你的前端代码调用一个Callable代码(this.functions.httpsCallable('getDirections');)。

您应该调整其中一个,最可能的是将您的云函数调整为可调用的(以获得可调用的优势),按照以下行:

export const getDirections = functions.region('europe-west6').onCall((data, context) => {
const lat1: number = +(data.lat1 ?? '0');
const lng1: number = +(data.lng1 ?? '0');
// ...
//Do something with lat/lng
return {
answer: answer,
};
});

最新更新