Cors 请求阻止的 Firebase 函数

Posted

技术标签:

【中文标题】Cors 请求阻止的 Firebase 函数【英文标题】:Cors Request Blocked Firebase Functions 【发布时间】:2020-09-02 14:31:23 【问题描述】:

我正在尝试在我的网站中使用 http 功能,但无法通过 CORS

这是我用来提交表单的 html 函数:

function uploadFile() 
      var file = document.getElementById("file_input").files[0];
      var pass = document.getElementById("pass").value;
      console.log(file + pass);
      // alert(file.name+" | "+file.size+" | "+file.type);
      var formdata = new FormData();
      formdata.append("file", file);
      formdata.append("password",pass);
      var ajax = new XMLHttpRequest();
      ajax.upload.addEventListener("progress", progressHandler, false);
      ajax.addEventListener("load", completeHandler, false);
      ajax.addEventListener("error", errorHandler, false);
      ajax.addEventListener("abort", abortHandler, false);
      ajax.open("POST", "https://us-central1-myAPPHERE.cloudfunctions.net/test"); 
       //ajax.setRequestHeader("Content-Type", "multipart/form-data");
      ajax.send(formdata);
     

这是服务器端代码:

functions = require('firebase-functions');
var  performance  = require('perf_hooks');
var begin;
var Busboy;
var path;
var os;
var fs;
var init = false;
var cors;

exports.test = functions.https.onRequest((req, res) => 

  res.set('Access-Control-Allow-Origin', '*');

  if (req.method === 'OPTIONS') 
    res.set('Access-Control-Allow-Methods', 'POST');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
   else     
    if (init === false) 
      begin = require('./Include/process');
      Busboy = require('busboy');
      path = require('path');
      os = require('os');
      fs = require('fs');
      cors = require('cors')( origin: true );
      init = true;
    

    var c1 = performance.now();
    const busboy = new Busboy( headers: req.headers );
    const fields = ;
    const tmpdir = os.tmpdir();
    const uploads = ;
    const fileWrites = [];
    var pass = '';

    busboy.on('file', (fieldname, file, filename) => 

      console.log(`Processed file $filename`);
      const filepath = path.join(tmpdir, filename);
      uploads[fieldname] = filepath;

      const writeStream = fs.createWriteStream(filepath);
      file.pipe(writeStream);

      const promise = new Promise((resolve, reject) => 
        file.on('end', () => 
          writeStream.end();
        );
        writeStream.on('finish', resolve);
        writeStream.on('error', reject);
      );
      fileWrites.push(promise);
    );

    busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) 
      pass = val;
    );

    busboy.on('finish', function () 
      console.log('Done parsing form!');
      console.log(pass);
      console.log(uploads);

      begin.processCard(uploads['file'], pass, 2).then((s) => 
        res.end(`
        <!DOCTYPE html>
        <html>
           <body>
              PDF Cropped in $performance.now() - c1!!
              <img src="data:image/jpeg;base64,$s" ></img> 
           </body>
        </html>
        `);
        // res.end(s)
      ).catch((err) =>  res.end('Error: ' + err) );
    );
    busboy.end(req.body);
  
); 

尝试提交表单会记录此 CORS 错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myAPPHERE.cloudfunctions.net/test. (Reason: CORS request did not succeed).

【问题讨论】:

【参考方案1】:

使用 HTTP Cloud Function,您需要执行以下操作,请参阅doc。

const functions = require('firebase-functions');
//...
const cors = require('cors')( origin: true );


exports.test = functions.https.onRequest((req, res) => 
  cors(req, res, () => 

     //... Your code here

  );
);

【讨论】:

CORS 标头“Access-Control-Allow-Origin”缺失,但我已在服务器中配置它 @jecol 尝试将此代码添加到服务器端代码后,您是否收到新的错误消息? 为什么这是必要的?我的函数是通过 httpS 和 firebase.functions().httpsCallable() 调用的。我按照这里的说明进行操作,他们没有提到 CORS。 firebase.google.com/docs/functions/get-started【参考方案2】:

您还需要允许 OPTIONS 方法,

浏览器xmlhttprequest默认会先发送options请求,然后才是实际请求

res.set('Access-Control-Allow-Methods', 'POST,OPTIONS');

更多详情请至Cors Standard 关于预检部分的跨源请求

【讨论】:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myApp.cloudfunctions.net/test. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) 仍然收到此错误 这个错误意味着,您在服务器配置中缺少“Access-Control-Allow-Origin”标头,请将其设置为 Access-Control-Allow-Origin:'*',以启用所有来源访问您的服务器资源 它在那里,我已经在原帖中发布了真正的所有代码 你在使用 mozilla 吗?让 ajax= new XMLHttpRequest(mozSystem: true);可能如果您将 mozSystem 设置为 true,它将允许从浏览器读取远程资源 @rizesky 这个评论让我很开心。我在 Chrome 中测试了相同的功能,它没有问题。前几天我一直在 Firefox 中进行测试...

以上是关于Cors 请求阻止的 Firebase 函数的主要内容,如果未能解决你的问题,请参考以下文章

Firebase 函数中的 CORS

为啥一个 Firebase 函数被 CORS 阻止了?

从被 CORS 阻止的 Firebase 托管代码调用 Firebase 函数

如何在firebase函数中将参数传递给cors

Firebase 云功能:带有 CORS 阻止的总线男孩的 POST 方法

CORS 阻止访问资源:如何在 Firebase 云功能中修复?