【问题标题】:SyntaxError: Unexpected token - in JSON at position 0(Firebase,Busboy)SyntaxError: Unexpected token - 在 JSON 中的位置 0(Firebase,Busboy)
【发布时间】:2020-12-13 20:09:36
【问题描述】:

我正在尝试将图像上传给 firebase 上的用户 但是我无法弄清楚为什么当我向服务器发送请求时会出现此错误(SyntaxError: Unexpected token - in JSON at position 0)

此外,这是一条受保护的路线(用户需要先登录/注册),但如果用户未登录,我应该会收到类似“未经授权”的错误(就像我尝试做未经授权的事情时在其他路线上一样) ,但我从 Title 得到错误

你能建议我能做什么吗? 谢谢

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 - 在 JSON 中的位置 0

  在 JSON.parse ()
  在 createStrictSyntaxError (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\types\json.js:158:10)
解析时 (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\types\json.js:83:15)
  在 C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\body-parser\lib\read.js:121:18
  在 invokeCallback (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:224:16)
  完成(C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:213:7)
  在 IncomingMessage.onEnd (C:\Users\Marius\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\raw-body\index.js:273:7)
  在 IncomingMessage.emit (events.js:327:22)
  在 endReadableNT (_stream_readable.js:1221:12)
  在 processTicksAndRejections (internal/process/task_queues.js:84:21)
///

【问题讨论】:

  • Unexpected token - 在 JSON 中的位置 0,意味着有一个字符串您正在尝试解析并且不是有效的 JSON,您能否分享错误的确切堆栈跟踪以计算该变量跨度>
  • 当然,我添加到主题中,因为这里的字符太多
  • "Unexpected token - in JSON at position 0" 通常表示一个空文档。检查响应是否成功并且实际上是 JSON。
  • 显示所有中间件的快速设置,特别是你的身体解析器

标签: javascript node.js firebase busboy


【解决方案1】:

我认为问题在于当我尝试发送请求(表单数据并在 Postman 上上传图片)时,它会在其他路线上给出相同的问题,我预计会出现另一个错误或类似的东西))

感谢大家的宝贵时间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2022-08-12
    • 2021-09-30
    • 2021-10-19
    相关资源
    最近更新 更多