mongoose 中间件未解析数据

rqdpfwrv  于 2023-05-23  发布在  Go
关注(0)|答案(1)|浏览(138)

为什么我的表单数据没有被添加到发送到MongoDB云的对象中。它发送一个空对象。但是如果我硬编码它们被添加的值:
这将发布一个空对象{}:

const formData = new FormData({
    firstName: firstName,
    lastName: lastName,
    email: email
  });

结果:

{}
{ _id: new ObjectId("646afa5f7d803b6059b0208f"), __v: 0 }

但这将成功发布硬编码字段:

const formData = new FormData({
firstName: "firstName",
lastName: "lastName",
email: "email"});

结果:

{}
    {
  firstName: 'firstName',
  lastName: 'lastName',
  email: 'email',
  _id: new ObjectId("646afaaed9b1db5dc17dd306"),
  __v: 0
  }

下面是我的models/formModel.js:

const mongoose = require('mongoose')

// Create a schema for the data you want to save in MongoDB
const formDataSchema = new mongoose.Schema({
  firstName: {
    type: String,
    // required: true
  },
  lastName: {
    type: String,
    // required: true
  },
  email: {
    type: String,
    // required: true
  }
});

module.exports = formDataSchema;

下面是我的app.js:

const express = require("express");
const path = require("path");
const connect = require('./config/db')
const mongoose = require("mongoose");
const formDataSchema = require("./models/formModel");

const app = express();
app.use(express.json())
connect();
app.use(express.static(path.join(__dirname, "public")));

app.get("/favicon.ico", (req, res) => {
  res.redirect("/index.html");
});

app.post("/signup", async (req, res) => {
  const { firstName, lastName, email } = req.body;
  console.log(req.body)
  const FormData = mongoose.model("FormData", formDataSchema);
  
  const formData = new FormData({
    firstName: firstName,
    lastName: lastName,
    email: email
  });
  
  
  try {
    const savedData = await formData.save();
    console.log(savedData);
    res.redirect('/success.html');
  } catch (error) {
    console.error(error);
    res.redirect('/fail.html');
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on ${PORT}`));

下面是index.html:

<form action="/signup" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <input type="text" name="firstName" id="first-name" class="form-control"
            placeholder="First Name" />
    </div>
    <div class="form-group">
        <input type="text" name="lastName" id="last-name" class="form-control"
            placeholder="Last Name" />
    </div>
    <div class="form-group">
        <input type="email" name="email" id="email" class="form-control" placeholder="Email" />
    </div>
    <button type="submit" class="btn btn-primary btn-block"> SUBMIT </button>
</form>

我怀疑问题在于表单数据如何发送到post方法。当我控制台日志req. body时,我只能根据空括号判断出似乎没有发送任何内容。

a11xaf1n

a11xaf1n1#

你有两个问题。。

  1. Express应用程序仅配置为处理application/json请求正文,因为您仅添加了以下正文解析中间件
app.use(express.json())

1.您的表单将请求正文作为multipart/form-data发送,这需要像Multer这样的特殊中间件。
通常情况下,您只需在上传文件时使用multipart/form-data
要解决这些问题,请将enctype="multipart/form-data"<form>中删除,或将其替换为enctype="application/x-www-form-urlencoded"(这是default value),并添加以下正文解析中间件

app.use(express.urlencoded());

相关问题