首页 > 解决方案 > 如何解决发布请求失败 ReactJS 和 ExpressJS

问题描述

所以我正在学习 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;

标签: node.jsreactjsmongodbexpressmongoose

解决方案


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

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

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


推荐阅读