angular - 在本地主机上开发时如何使用 AngularFire 函数允许 CORS
问题描述
我在离子/角度应用程序中使用 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);
});
解决方案
您实际上是在混合HTTP Cloud Functions和Callable Cloud Functions。
您的 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,
};
});
推荐阅读
- javascript - Web-Push 通知脚本在 Firefox 上工作,但在 Chrome 上不工作
- asp.net - 日期时间 - ModelState.IsValid 错误
- google-chrome - 如何在谷歌浏览器中禁用站点隔离?
- ios - UITableview中如何设计多个单元格的数组结构?
- sql - 使用子查询在同一张表上左连接
- trace - 如何以 csv 格式重放块 I/O 跟踪文件
- c# - 为什么我们不需要 DSN 来通过 ODBC 连接到 SQL Server (C#)
- visual-studio - Visual Studio Post Build 事件(如果存在)
- angular - Angular4 - p-menu 无法在菜单栏上看到图标
- android - 如何压缩使用 Glide 加载的可绘制图像