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)