首页 > 解决方案 > Firebase 云功能:带有 CORS 阻止的总线男孩的 POST 方法

问题描述

使用带有 Firebase 云功能的 busboy 具有上传功能我不断收到此错误

从源“localhost”访问“firebase cloud functions url”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经包含了cors:

app.use(cors());

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers,  Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,   Access-Control-Request-Headers');
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

我不确定是不是因为我仍在使用免费版本...因为我的简单 GET api 有效..

我也遇到了这个错误,但我不确定是不是因为 CORS 阻止了图片上传。

TypeError:无法读取 null 的属性“文件”

这是我的代码:

const fs = require("fs");
const os = require("os");
const path = require("path");
const Busboy = require("busboy");

 const busboy = new Busboy({ headers: req.headers });
  let uploadData = null;
  let origFileName;

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    origFileName = filename
    const filepath = path.join(os.tmpdir(), filename);
    uploadData = { file: filepath, type: mimetype };
    file.pipe(fs.createWriteStream(filepath));
  });

  busboy.on("finish", () => {
    const bucket = gcs.bucket(bucketName);
    let uuid = UUID();

    bucket
      .upload(uploadData.file, {
        uploadType: "media",
        metadata: {
          metadata: {
            contentType: uploadData.type,
            firebaseStorageDownloadTokens: uuid
          }
        },

当我使用邮递员时没有遇到错误。

任何帮助,将不胜感激..

标签: node.jsfirebasecorsgoogle-cloud-functions

解决方案


终于找到答案了。从反应发布时,内容类型应该是“multipart/form-data”而不是“application/x-www-form-urlencoded”。


推荐阅读