mern堆栈,axios posthttp://localhost:8000/video/uploadvideo 400(错误请求)

5jvtdoz2  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(185)

我使用npm run dev在一个文件夹上同时运行客户端和服务器。axios请求的基本url是后端端口。我看过axios导入直接从“axios”导入axios的视频,但每次我尝试时,它都会说找不到,所以对我有效的是从链接到后端本地主机的“../axios”导入axios。我正在尝试创建一个视频上传网站,当我删除文件时,它可以工作,并说文件成功,但当我点击提交时,它不工作
下面是upload.js组件

const onSubmit = (event) => {
    event.preventDefault();

    const variables = {
      writer: user.result.googleId || user.result._id,
      caption: caption,
      privacy: privacy,
      filePath: filePath,
      happiness: happiness,
      motivation: motivation,
      goals: goals,
    };

    axios.post("/video/uploadVideo", variables).then((response) => {
      if (response.data.success) {
        alert("video Uploaded Successfully");
        history.push("/");
      } else {
        console.log(response.data);
        alert("Failed to upload video");
      }
    }); 

  const onDrop = (files) => {
    let formData = new FormData();
    const config = {
      header: { "content-type": "multipart/form-data" },
    };
    const [uploadedFile] = files;
    setFile(uploadedFile);
    console.log(files);
    formData.append("file", files[0]);

    axios.post("/video/uploadfiles", formData, config).then((response) => {
      if (response.data.success) {
        let variable = {
          filePath: response.data.filePath,
          fileName: response.data.fileName,
        };
        setFilePath(response.data.filePath);
        console.log("success upload");

        //gerenate thumbnail with this filepath !
      } else {
        alert("failed to save the video in server");
        console.log(response.data);
      }
    });
  };

ondrop func可以正常工作,但onsubmit给出了错误的请求错误
这是bckend中的server.js文件

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import data from "./data.js";
import Videos from "./dbModel.js";
import postRoutes from "./routes/posts.js";
import userRouter from "./routes/user.js";
import videoRouter from "./routes/video.js";

const app = express();
const port = process.env.PORT || 8000;

//Middlewares
app.use(express.json());
app.use(cors());
app.use("/posts", postRoutes);
app.use("/user", userRouter);
app.use("/video", videoRouter);

app.use("/uploads", express.static("uploads"));

if (process.env.NODE_ENV === "production") {
  // Set static folder
  app.use(express.static("client/build"));

  // index.html for all page routes
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

//db config
const CONNECTION_URL =
  "mongodb+srv://dimerson:9zRHuVcHLh5fSznu@cluster0.5n5rb.mongodb.net/KweebleDatabase?retryWrites=true&w=majority";
mongoose.connect(CONNECTION_URL, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});

app.get("/", (req, res) => res.status(200).send("hello world"));

app.get("/v1/posts", (req, res) => res.status(200).send(data));
app.post("/v2/posts", (req, res) => {
  const dbVideos = req.body;
  Videos.create(dbVideos, (err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(201).send(data);
    }
  });
});

app.get("/v2/posts", (req, res) => {
  Videos.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });
});

app.listen(port, () => console.log(`listening on localhost:${port}`));

这是routes/video.js文件

import express from "express";
import multer from "multer";
import Video from "../models/Video.js";

const router = express.Router();

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}_${file.originalname}`);
  },
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    if (ext !== ".mp4" || ext !== ".MP4" || ext !== ".mov" || ext !== ".MOV") {
      return cb(res.status(400).end("only video files allowed"), false);
    }
    cb(null, true);
  },
});

let upload = multer({ storage: storage }).single("file");

router.post("/uploadfiles", (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      return res.json({ success: false, err });
    }
    return res.json({
      success: true,
      filePath: res.req.file.path,
      fileName: res.req.file.filename,
    });
  });
});

router.post("/uploadVideo", (req, res) => {
  const video = new Video(req.body);

  video.save((err, video) => {
    console.log(res.data);
    if (err) return res.status(400).json({ success: false, err });
    return res.status(200).json({ success: true });
  });
});

export default router;

这是models/video.js文件

import mongoose from "mongoose";
const Schema = mongoose.Schema;

const videoSchema = mongoose.Schema(
  {
    writer: {
      type: Schema.Types.ObjectId,
      ref: "User",
    },
    // video: { type: String, required: true },
    caption: {
      type: String,
    },
    privacy: {
      type: Number,
    },
    happiness: { type: String },
    motivation: { type: String },
    goals: { type: String },
    filePath: {
      type: String,
    },
    catogory: String,
    views: {
      type: Number,
      default: 0,
    },
  },
  { timestamps: true }
);

export default mongoose.model("Video", videoSchema);

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题