【问题标题】:Firebase project works locally but deployed version outputs CORS errorFirebase 项目在本地工作,但部署的版本输出 CORS 错误
【发布时间】: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"
          }
        ]
      }
    ]
  }
}

【问题讨论】:

    标签: firebase cors preflight


    【解决方案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'
    }));
    

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2023-01-11
      • 2020-01-07
      • 1970-01-01
      • 2018-07-28
      • 2017-06-14
      • 2020-10-26
      • 2021-08-19
      • 2020-12-17
      相关资源
      最近更新 更多