NodeJS 节点类型错误:餐馆工不是构造工

2guxujil  于 2023-01-16  发布在  Node.js
关注(0)|答案(2)|浏览(100)

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

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
我也运行了这个,但是它对我不起作用。任何解决这个错误的帮助都将非常感谢--我有点被它卡住了。
server.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);
 });

client.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>
esyap4oy

esyap4oy1#

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

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

但是你说你试过了,但是没有成功。那是什么错误呢?

qkf9rpyu

qkf9rpyu2#

你可以试着把版本降低到0.3.1,npm i busboy@0.3.1,我刚刚降低了版本。

相关问题