问题描述
我正在尝试将图像上传到Firebase上的用户 但是我无法弄清楚为什么向服务器发送请求时会出现此错误(SyntaxError:意外令牌-JSOn位置0)
此外,这是一条受保护的路由(用户需要先登录/注册),但是如果用户未登录,则应该得到类似“未经授权”的错误(就像在其他路线上尝试未经授权的操作一样) ,但我从标题中得到了错误
您能建议我可以做什么吗? 谢谢
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);
};
来自邮递员: ///
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)
解决方法
我认为问题是当我尝试发送请求(在Postman上发送表单数据并上传图片)时,导致它在其他路线上也出现了相同的问题,我希望会遇到其他错误或类似的问题))
谢谢大家的时间