MongoServerSelectionError:在超时时连接 ECONNREFUSED 127.0.0.1:27017._onTimeout

问题描述 投票:0回答:0

为什么我会收到这个错误?

我正在尝试使用表单数据将我在前端的音频文件发送到后端,在那里我使用 multer 和 gridfs 将文件发送到 mongoDB。尝试使用音频文件执行此操作时遇到了很多问题。

为什么我会收到这个错误?我正在尝试发送音频文件。我在前端使用表单数据到后端,在那里我使用 multer 和 gridfs 将文件发送到 mongoDB。尝试使用音频文件执行此操作时遇到了很多问题。

App.js

import React, { useState } from 'react';

function AudioUpload() {
  const [file, setFile] = useState(null);

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('audio', file);

    try {
      const response = await fetch('http://localhost:4003/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div>
    <form onSubmit={handleSubmit}>
      <div>
        <input type="file" id="audio" name="audio" accept="audio/*" onChange={handleFileChange} />
      </div>
      <button type="submit" disabled={!file}>Upload</button>
    </form>
    </div>
  );
}

export default AudioUpload;

Server.js
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const Grid = require('gridfs-stream');
const { GridFsStorage } = require('multer-gridfs-storage');
const cors = require("cors");
const app = express();
app.use(cors());

const conn = mongoose.createConnection('mongodb+srv://jordandeeds31:[email protected]/grid2?retryWrites=true&w=majority', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let gfs;

conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('audioFiles');
  console.log("connected to db");
});

const storage = new GridFsStorage({
  url: 'mongodb://localhost/mydatabase',
  file: (req, file) => {
    return {
      filename: file.originalname,
      bucketName: 'audioFiles',
    };
  },
});

const upload = multer({ storage: storage });

const audioSchema = new mongoose.Schema({
  filename: { type: String, required: true },
  contentType: { type: String, required: true },
  fileId: { type: mongoose.Schema.Types.ObjectId, required: true },
});

const Audio = conn.model('Audio', audioSchema);

app.post('/upload', upload.single('audio'), async (req, res) => {
  try {
    const { originalname, mimetype } = req.file;
    const fileId = req.file.id;
    const audio = new Audio({
      filename: originalname,
      contentType: mimetype,
      fileId,
    });
    await audio.save();
    res.status(200).json({ message: 'File uploaded successfully' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error uploading file' });
  }
});

app.listen(4003, () => {
  console.log('Server listening on port 4003');
});
node.js reactjs multipartform-data multer gridfs
© www.soinside.com 2019 - 2024. All rights reserved.