【问题标题】:Nodejs TypeError: Busboy is not a constructorNodejs TypeError:Busboy 不是构造函数
【发布时间】:2023-01-16 14:01:14
【问题描述】:

我正在通过一些教程来构建一个带有文件上传的聊天服务器。我以前没有使用过 NodeJS 的经验,我一直在遵循讲师的代码,但最近遇到了一个我无法解决的障碍。尝试通过 npm run dev 构建项目以运行测试脚本时,出现以下错误。它想要接收文件上传到我项目中的上传文件夹中:

控制台日志代码:

TypeError: Busboy is not a constructor
    at C:\Users\xxx\Desktop\chat\server.js:24:20

在 chrome 开发工具中

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

我在网上找到的答案似乎我必须更改代码,我必须改为调用它:

const busboyCons = require('busboy');
...
var busboy = busboyCons({ headers: req.headers });

来源:https://gist.github.com/shobhitg/5b367f01b6daf46a0287

我也运行了这个,但它对我不起作用。任何解决此错误的帮助将不胜感激 - 我有点坚持它。

服务器.js:

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

const path = require('path');
const http= require('http').createServer(app);
const PORT=process.env.PORT || 3000;
const io=require('socket.io')(http);
const fs = require('fs');
const Busboy = require('busboy');

app.use(express.static(__dirname + '/public'))
app.use(express.static('uploads'))

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
  });
  
  app.get('/css/main.css', function(req, res) {
    res.sendFile(__dirname + "/public" + "/style.css");
  });

  app.post('/upload', function(req, res) {
    const busboy = new Busboy({ headers: req.headers });
    req.pipe(busboy);
    busboy.on('file', ( fieldname, file, filename) => {
      const ext = path.extname(filename);
      const newFilename = `${Date.now()}${ext}`;
      req.newFilename = newFilename;
      req.originalFilename = filename;
      const saveTo = path.join('uploads', newFilename);
      file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', () => {
      res.json({
        originalFilename: req.originalFilename,
        newFilename: req.newFilename
      });
    });
  });


  io.on('file', f => {
    console.log(`File by: ${f.userName}`);
    socket.emit('file', f);
 });


客户端.js:

const socket = io()


let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let formAreaFileUpload=document.querySelector('.submitMediaFiles')
let formSubmit=document.querySelector('#form')

// preventDefault();


formSubmit.addEventListener("submit",handleFormSubmit)

function handleFormSubmit(e) {
    e.preventDefault();

    console.log(e)
    const form = $(this);
    const formData = new FormData(form[0])
    for (const p of formData) {
      if (p[1].size <= 0) {
        return
      }
    }
    $.ajax({
      method: 'POST',
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      url: '/upload',
      success: handleUploadSuccess,
    })
  }


  function handleUploadSuccess(resp) {
    socket.emit('file', { userName, file: { url: `/${resp.newFilename}`, filename: resp.originalFilename } });


  }

index.html(截图):

<form id="form" style="background-color: #999999">
            <div class="contentLine">
              
            <div class="column">
              <input id="data" type="file" name="file" />
            </div>
          <div class="column last">
            <button style="float:right" type="submit">Send Multimediafile </button>
           
        
          </div>
            </div>
          </form>
        


    </section>

    <script src="/socket.io/socket.io.js"></script>
    <script src="/client.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 

【问题讨论】:

  • 你有没有找到解决办法?
  • 你弄清楚这个问题了吗?我正在使用打字稿,早些时候我认为这可能是打字问题,但这是另外一回事。 busboy: 1.0.0 @types/busboy: ^1.5.0 NodeJs: 14.19.3

标签: node.js socket.io busboy


【解决方案1】:

根据文档,您应该以这种方式使用 busboy:

const busboy = require('busboy');
const bb = busboy({ headers: req.headers });

但是你说你试过了,但没有用。然后发生了什么错误?

【讨论】:

  • 嗨,它还说 busboy 不是构造函数,我从 iabhishek.dev/post/… 获得了教程
  • 嗨,这很奇怪,因为我没有错误。您使用的是哪个版本的 busboy?
  • 版本 1.5.0,是否在您的示例中将图片上传到上传文件夹?
  • 您使用的是什么版本?
  • 1.5.0版本也是。不,我刚刚测试了 busboy 包,这里是源代码:stackblitz.com/edit/node-hvyrlt 您可以运行代码,看到显示的错误与“Busboy 不是构造函数”不同
【解决方案2】:

您可以尝试将版本降低到 0.3.1,npm i busboy@0.3.1。我只是降低了版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 2018-05-24
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多