【发布时间】:2021-02-16 06:30:09
【问题描述】:
我有一个 Firebase 项目,其中包含前端托管和一个云功能来处理所有后端请求。当我做 firebase 服务并在 localhost 上运行项目时,一切都很好。但是,部署后,当我尝试在线访问它时,出现以下错误。
对 XMLHttpRequest 的访问已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
我已经尝试了所有在 firebase 中启用 CORS 的解决方案,但错误并没有消失。是什么导致了这个错误,我该怎么办?
云功能的 app.js 中的相关代码(index.js 等效项)
const functions = require('firebase-functions');
var express = require('express');
var cors = require("cors");
// These contain all the POSTS for the backend
var routes = require('./server/routes/routes');
var api = require('./server/routes/api');
var app = express();
app.use('/routes', routes);
app.use('/api', api);
app.use(cors({ origin: true }));
exports.app = functions.region('europe-west2').https.onRequest(app);
firebase.json
{
"hosting": {
"public": "public/client/dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "/api/**",
"function": "app"
},
{
"source": "/routes/**",
"function": "app"
},
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/**",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache, no-store, must-revalidate"
}
]
},
{
"source":
"**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|eot|otf|ttf|ttc|woff|woff2|font.css)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=604800"
}
]
}
]
}
}
【问题讨论】: