我有一个Firebase项目,其中托管了前端,还有一个云功能来处理所有后端请求。当我执行firebase服务并在localhost上运行项目时,一切都很好。但是,部署后,当我尝试在线访问它时,出现以下错误。
CORS策略已阻止对XMLHttpRequest的访问:对 预检请求未通过访问控制检查:否 请求中出现“ 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"
}
]
}
]
}
}
答案 0 :(得分:-1)
跨域资源共享(CORS)允许AJAX请求跳过同域策略并从远程主机访问资源。
The * wildcard allows access from any origin
app.use(cors({
origin: '*'
}));
If you want to restrict AJAX access to a single origin, you can use the origin
app.use(cors({
origin: 'http://yourapp.com'
}));
要通过CORS启用HTTP cookie
app.use(cors({
credentials: true,
origin: '*'
}));
OR
app.use(cors({
credentials: true,
origin: 'http://yourapp.com'
}));