Search code examples
node.jsfirebaseexpresspostmanbusboy

Busboy seems to be causing an internal server error when requiring it in my uploadImage function for Firebase


I've spent pretty much all day trying to figure out how to successfully upload photos into my storage and database, and so far I can't even get one to be successful!

Essentially I'm using postman to send a post request with an image file attached. I think I hit all the point as in I have the content type set to multipart/form-data, I have the body tab on form-data, and I have the row with my file set to file and not text. Photo of postman request and error

And this internal server error is the issue that I can't resolve.

Now In my function below, I require busboy and at that point is where the internal server error occurs, if I place a return before that, then it will return. But if I place a return after this is declared, this error occurs.

const { admin, db } = require('../util/admin');
const config = require("../util/config");

...

exports.uploadImage = (req, res) => {

  // res.send("this worked"); // everything works up to this point

  const Busboy = require("busboy");

  const path = require("path");

  const os = require("os");

  const fs = require("fs");

  const busboy = new Busboy({ headers: req.headers });

  let imageToBeUploaded = {};
  let imageFileName;

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    console.log(fieldname, file, filename, encoding, mimetype);
    if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
      return res.status(400).json({ error: "Wrong file type submitted" });
    }
    // my.image.png => ['my', 'image', 'png']
    const imageExtension = filename.split(".")[filename.split(".").length - 1];
    // 32756238461724837.png
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`;
    const filepath = path.join(os.tmpdir(), imageFileName);
    imageToBeUploaded = { filepath, mimetype };
    file.pipe(fs.createWriteStream(filepath));

  });
  busboy.on("finish", () => {
    admin
      .storage()
      .bucket()
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype
          }
        }
      })
      .then(() => {
        const images = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
        return db.doc(`/posts/${req.params.postId}`).update({ images });
      })
      .then(() => {
        return res.json({ message: "image uploaded successfully" });
      })
      .catch(err => {
        console.error(err);
        return res.status(500).json({ error: "something went wrong" });
      });
  });
  busboy.end(req.rawBody);
};

And here's my index file included

const functions = require('firebase-functions');

const app = require('express')();

const FBAuth = require('./util/fbAuth')

const { getAllPosts, createOnePost, getThePost, deletePost, uploadImage } = require('./handlers/posts');
const { login } = require('./handlers/users');

// Posts Routes

app.get('/posts', getAllPosts);
app.get('/post/:postId', getThePost);
app.post("/post", FBAuth, createOnePost);
app.delete('/post/:postId', FBAuth, deletePost);
app.post('/post/:postId/image', FBAuth, uploadImage);

//TODO update post

// Login Route

app.post('/login', login)

exports.api = functions.https.onRequest(app)

The it seems there's something going on when I declare busboy in my function that is causing the error. And I have no idea why.

I should mention that the code seemed to run when I was using a localhost with "$ firebase serve", but the jpeg images weren't really showing up in the firestorage.

I really appreciate any help you all can offer, and please feel free to ask for more information!


Solution

  • I don't see anything in the code that would be causing an internal server error. I imagine you don't actually have busboy installed with npm. Have you gone into your functions folder and typed "npm install busboy"?