英文:
Data not being parsed by middleware
问题
The issue might be related to how you're handling the form data. It seems like you're using FormData
incorrectly. Instead, you should be using an object to send data in your request. Here's a corrected example of how to send the data:
const formData = {
firstName: firstName,
lastName: lastName,
email: email
};
Make sure you update this part of your code, and it should send the form data correctly to your POST method in Express.
英文:
Why isn't my form data being added to the object sent to MongoDB cloud. It sends an empty object. But if I hard code the values they are added:
This posts an empty object {}:
const formData = new FormData({
firstName: firstName,
lastName: lastName,
email: email
});
Result:
{}
{ _id: new ObjectId("646afa5f7d803b6059b0208f"), __v: 0 }
But this will post hardcoded fields successfully:
const formData = new FormData({
firstName: "firstName",
lastName: "lastName",
email: "email"});
Result:
{}
{
firstName: 'firstName',
lastName: 'lastName',
email: 'email',
_id: new ObjectId("646afaaed9b1db5dc17dd306"),
__v: 0
}
Here is my 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;
Here is my 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}`));
Here is 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>
I suspect the issue is in how the form data is sent to the post method. I can only tell that it looks like nothing is being sent based on the empty brackets when I console log req.body.
答案1
得分: 0
你的Express应用仅配置为处理application/json
请求体,因为你只添加了以下的body解析中间件:
app.use(express.json())
你的表单以multipart/form-data
形式发送请求体,这需要像Multer这样的特殊中间件。
通常,只有在上传文件时才需要使用multipart/form-data
。
为解决这些问题,请从你的<form>
中移除enctype="multipart/form-data"
,或将其替换为enctype="application/x-www-form-urlencoded"
(这是默认值),并添加以下的body解析中间件:
app.use(express.urlencoded());
英文:
You have two issues...
-
Your Express app is only configured to handle
application/json
request bodies because you have only added the following body-parsing middleware>
lang-js
> app.use(express.json())
> -
Your form is sending the request body as
multipart/form-data
which requires special middleware like Multer.Typically, you only need to use
multipart/form-data
when uploading files.
To solve these, remove enctype="multipart/form-data"
from your <form>
or replace it with enctype="application/x-www-form-urlencoded"
(this is the default value) and add in the following body-parsing middleware
app.use(express.urlencoded());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论