如何解决请求后失败的ReactJS和ExpressJS

时间:2020-08-29 03:39:50

标签: node.js reactjs mongodb express mongoose

所以我正在学习Express和Mongoose的工作方式,所以我试图向服务器端发出Post请求,然后将内容保存到MongoDB,所以我不知道抛出的错误是什么,但是当我检查它创建条目的数据库,但只有空条目,没有任何来自客户端/表单的信息被保存到数据库中

当我注销从服务器端接收到的数据时,这就是我得到的:

Results: { _id: 5f49d245afcfaa2168ad4d3f, __v: 0 }

只需输入一个带有ID的空条目

我的服务器端代码:

//Initializing all dependencies
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const cors = require("cors");

app.use(cors());
//Getting the body-paser set up for post request
app.use(bodyParser.json());

//Making a connection to DB via mongoose
mongoose.connect("mongodb://localhost:27017/LectureVideos", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

/* 
  - Creating my database schema that will be having the following contents
  ---->Schema:
  ------->1. lecturer : type --> String
  ------->2. module   : type --> String
  ------->3. video    : type --> Buffer/File
*/
const lectureSchema = mongoose.Schema({
  lecturer: String,
  module: String,
  video: {
    data: Buffer,
    contentType: String,
  },
});

const LectureVideos = mongoose.model("LectureVideos", lectureSchema);

app.post("/upload-lecture/", (request, response) => {
  const addLectureVideo = new LectureVideos({
    lecturer: request.body.lecturer,
    module: request.body.module,
    video: request.body.video,
  });

  addLectureVideo.save((error, data) => {
    if (error) {
      return console.log(error);
    }
    console.log(data);
  });
});

app.listen(3001);

到处理上传系统的客户端的密码

import React, { Component } from "react";
import axios from "axios";

class Upload extends Component {
  constructor(props) {
    super(props);

    this.state = {
      lecturer: "",
      module: "",
      video: null,
    };
    this.handleChange = this.handleChange.bind(this);
    this.uploadVideo = this.uploadVideo.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.id]: e.target.value,
    });
  }

  uploadVideo(e) {
    e.preventDefault();
    const form_data = new FormData();
    form_data.append("lecturer", this.state.lecturer);
    form_data.append("module", this.state.module);
    form_data.append("video", this.state.video);
    const url = "http://127.0.0.1:3001/upload-lecture/";
    axios
      .post(url, form_data)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    return (
      <div className="form__container">
        <form className="form" onSubmit={this.uploadVideo}>
          <h3>Lecturer</h3>
          <input
            type="text"
            id="lecturer"
            onChange={this.handleChange}
            placeholder="Lecturer"
          />

          <h3>Module</h3>
          <input
            type="text"
            id="module"
            onChange={this.handleChange}
            placeholder="module"
          />

          <h3>Video</h3>
          <input type="file" id="video" onChange={this.handleChange} />

          <button onClick={this.uploadVideo}>Upload Video</button>
        </form>
      </div>
    );
  }
}

export default Upload;

1 个答案:

答案 0 :(得分:0)

您可以尝试使用express.json()中间件或类似bodyParser的中间件来解析请求正文

app.use(express.json()) or app.use(bodyParser.json())

注意:我认为您应该将猫鼬模式字段设置为必需,以便进行更多数据验证,然后再将其保存到数据库中,以避免类似的事情。