我知道有很多CORS帖子和解决方案,我已经看过很多次了。没有运气在几个小时后解决我的CORS问题,我决定在这里发布:(
我的客户角度法导入并初始化包
...import { AngularFireFunctions } from "@angular/fire/functions";
constructor(...
private afn: AngularFireFunctions,
) {}
initCloudFunctions() {
let cmd = "helloWorld";
const callable = this.afn.httpsCallable(cmd);
let data = callable({ name: "some-data" }).subscribe({
next(res) {
console.log("res: ", res);
},
error(msg) {
console.log("Error : ", msg);
}
});
}
我的火球云函数(TypeScript(,index.ts
export const helloWorld = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
// let url = 'https://a1rvv0rk2.stackblitz.io/main/firecp'
// response.set('Access-Control-Allow-Origin', url);
response.set('Access-Control-Allow-Credentials', 'true');
response.set('Access-Control-Allow-Headers', 'Content-Type')
response.send("Hello from Firebase! " + new Date());
});
我使用了通配符,但我仍然得到CORS错误
在'获取的访问权限https://...my项目…cloudfunctions.net/helloWorld"来自原点"https://..my项目….stackblitz.io'已被CORS策略阻止:请求标头中的Access Control Allow Headers不允许字段授权飞行前反应。zone.js:1118岗位https://...my项目..cloudfunctions.net/helloWorld net::ERR_FAILED
如果我能从大师那里得到一些帮助,我真的很感激。
更新:感谢Doug和来自youtube的Lars,我成功地导入了CORS!这是我更新的代码,希望它能帮助那些使用TypeScript而不是JavaScript 的人
导入CORS库
import * as corsModule from 'cors'
const cors = corsModule(({ origin: true }))
云功能
export const helloWorldWithCORS = functions.https.onRequest((request, response) => {
// ref: https://github.com/firebase/firebase-js-sdk/issues/1338#issuecomment-461234192
cors(request, response, () => {
response.status(200).send({data: { success: true, message: 'yeah!' }})
})
});
Angular应用程序
async initCloudFunctions() {
// let cmd = "helloWorld";
let cmd = "helloWorldWithCORS";
const callable = this.afn.httpsCallable(cmd);
this.data = await callable({name: 'some data'})
console.log(this.data)
}
尝试添加一个额外的允许标头:
response.set('Access-Control-Allow-Headers','Content-Type')
根据mozzilla文档,这应该是隐含的:
CORS安全列出的请求标头、Accept、Accept Language、Content Language、Content Type始终是允许的,不必按此标头列出。但是,请注意,这些标头也适用其他限制,您可以通过在Access Control Allow headers标头中列出这些标头来规避这些限制。
发件人:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
仍有可能存在额外的锁定