React js Request failed with status code 500 AxiosError: Request failed with status code 500

Всем привет, пытаюсь создать самый простой загрузчик файла, при попытке загрузки файла на сервер показывается ошибку Request failed with status code 500 AxiosError: Request failed with status code 500 . Либо загрузка файла просто зависает.

мой сервер файл Upload.js

    const multer = require("multer")
const storage = multer.diskStorage({
  //Specify the destination directory where the file needs to be saved
  destination: function (req, file, cb) {
    cb(null, "./uploads")
  },
  //Specify the name of the file. The date is prefixed to avoid overwriting of files.
  filename: function (req, file, cb) {
    cb(null, Date.now() + "_" + file.originalname)
  },
})

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

module.exports = upload

и файл index.js

   const express = require("express")
const upload = require("./upload")
const multer = require("multer")
const cors = require("cors")

const app = express()

//Add the client URL to the CORS policy
const whitelist = ["http://localhost:3000"]
const corsOptions = {
  origin: function (origin, callback) {
    if (!origin || whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error("Not allowed by CORS"))
    }
  },
  credentials: true,
}
app.use(cors(corsOptions))

app.post("/upload_file", upload.single("file"), function (req, res) {
  if (!req.file) {
    //If the file is not uploaded, then throw custom error with message: FILE_MISSING
    throw Error("FILE_MISSING")
  } else {
    //If the file is uploaded, then send a success response.
    res.send({ status: "success" })
  }
})

//Express Error Handling
app.use(function (err, req, res, next) {
  // Check if the error is thrown from multer
  if (err instanceof multer.MulterError) {
    res.statusCode = 400
    res.send({ code: err.code })
  } else if (err) {
    // If it is not multer error then check if it is our custom error for FILE_MISSING
    if (err.message === "FILE_MISSING") {
      res.statusCode = 400
      res.send({ code: "FILE_MISSING" })
    } else {
      //For any other errors set code as GENERIC_ERROR
      res.statusCode = 500
      res.send({ code: "GENERIC_ERROR" })
    }
  }
})

//Start the server in port 8081
const server = app.listen(8081, function () {
  const port = server.address().port

  console.log("App started at http://localhost:%s", port)
})

Ответы (0 шт):