Ad

Firebase Cloud Functions: POST Method With Bus Boy Blocked By CORS

Have a upload functionality using busboy with Firebase cloud functions I keep getting this error

Access to XMLHttpRequest at 'firebase cloud functions url' from origin 'localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already have cors included:

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();
});

I'm not sure if it's because I'm still using the free version... because my simple GET api works..

I also got this error but I'm not sure if it's because CORS block the image upload..

TypeError: Cannot read property 'file' of null

here's my code:

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
          }
        },

When I use postman no error encountered.

any help would be appreciated..

Ad

Answer

Finally found the answer.. content type should be "multipart/form-data" not "application/x-www-form-urlencoded" when posting from react.

Ad
source: stackoverflow.com
Ad