node.js - 在本地主机上运行时,Firebase 出现 CORS 错误

标签 node.js reactjs firebase

运行项目时出现以下错误。

Failed to load https://us-centralx-xxx.cloudfunctions.net/xxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.

阅读了很多SO帖子后,我找到了以下解决方案,我需要添加 Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-Headers

const HEADERS = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':  'http://localhost:3000/',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
};

但是,错误仍然存​​在。我该如何解决这个问题?

更新

exports.uploadFile = functions.https.onRequest((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*");

        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


    res.status(200).json({
        message: req.body
    });
});

最佳答案

在 Node.js 服务器中设置适当的 header 以允许受控的 CORS 请求:

app.use((req, res, next) => {
  const origin = req.headers.origin;
  // arrayOfValidOrigins is an array of all the URL from where you want to allow 
  // to accept requests. In your case: ['http://localhost:3000'].
  // In case you want to accept requests from everywhere, set:
  // res.setHeader('Access-Control-Allow-Origin', '*');
  if (arrayOfValidOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  // Here allow all the HTTP methods you want
  res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
  // Here you allow the headers for the HTTP requests to your server
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // Method to reference to the next Node.js function in your flow
  next();
});

您的另一个选择是使用 Express.js CORS package并根据您的需要进行配置。

关于node.js - 在本地主机上运行时,Firebase 出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204368/

相关文章:

javascript - NodeJs HTTPS 与快速生成器的连接

javascript - 使用 node.js 的 Windows 命令行解释器

javascript - 如何在一个渲染方法上显示多个对象的关键数据?

javascript - 如何在wix react native 导航中将数据从一个屏幕传递到另一个屏幕

swift - Firebase 太慢而无法加载基于图 block 的游戏

javascript - Mocha bdd 风格测试命名

javascript - 如何在nodejs中将UTF16文件转换为UTF8文件

javascript - 如何在一个onClick(ReactJS)中调用一个类和setState

firebase - Firestore 的 `documentSnapshot.toObject(className::class.java)` 如何重新分配在主构造函数中设置的 `val` 值?

java - 未获取 Firebase 数据库数据