1

I am trying to upload an image to a user on firebase But I can't figure out why I get this error when I send a request to the server( SyntaxError: Unexpected token - in JSON at position 0)

Also, this is a protected route(user needs to login/signup first), but if the user is not logged, I should get the error like "Unauthorized"(like on other routes when I try to do something unauthorized), but instead I get the error from Title

Can you please suggest what i can do? Thank you

exports.uploadImage = (req, res) => {
  const BusBoy = require("busboy");
  const path = require("path");
  const os = require("os");
  const fs = require("fs");

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

  let imageFileName;
  let imageToBeUploaded = {};

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
      return res.status(400).json({ error: "Wrong file type submitted" });
    }
    
    const imageExtension = filename.split(".")[filename.split(".").length - 1];
    
    imageFileName = `${Math.round(
      Math.random() * 100000000000
    )}.${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 imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
        return db.doc(`/users/${req.user.handle}`).update({ imageUrl });
      })
      .then(() => {
        return res.json({ message: "Image uploaded successfully" });
      })
      .catch((err) => {
        console.error(err);
        return res.status(500).json({ error: err.code });
      });
  });
  busboy.end(req.rawBody);
};

From Postman: ///

SyntaxError: Unexpected token - in JSON at position 0

   at JSON.parse (<anonymous>)
   at createStrictSyntaxError (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\types\json.js:158:10)
   at parse (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\types\json.js:83:15)
   at C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\read.js:121:18
   at invokeCallback (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:224:16)
   at done (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:213:7)
   at IncomingMessage.onEnd (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:273:7)
   at IncomingMessage.emit (events.js:327:22)
   at endReadableNT (_stream_readable.js:1221:12)
   at processTicksAndRejections (internal/process/task_queues.js:84:21)
///
cucereanum
  • 43
  • 8
  • 1
    Unexpected token - in JSON at position 0, means there is a string which you are trying to parse and is not a valid JSON, can you share exact stack trace of the error to figure that variable – r7r Aug 25 '20 at 07:52
  • Sure, i added to the topic cause here were too much characters – cucereanum Aug 25 '20 at 08:10
  • "Unexpected token - in JSON at position 0" usually means an empty document. Check that the response is successful and is actually JSON. – phuzi Aug 25 '20 at 09:13
  • Show the express setup with all the middleware specifically with your body parser – Lev Kuznetsov Aug 25 '20 at 09:50

1 Answers1

0

I think the issue is when i tried to send request (form-data and upload a picture on Postman) cause it gives the same issue on other routes which i expected to get another error or something like that ))

Thank all of you for your time

cucereanum
  • 43
  • 8