Firebase项目在本地工作,但部署的版本输出CORS错误

问题描述

我有一个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/**",{
        "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)","value": "max-age=604800"
          }
        ]
      }
    ]
  }
}

解决方法

跨域资源共享(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'
}));

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...