点播.主体是一个空对象express/nodejs



我有一个表单,有两个数字输入字段,我想发送到后端,但需要。身体永远是空的。这是我的表单:

<form
class="mt-3"
id="myForm"
enctype="multipart/form-data"
action="/submit-thing1and2"
>
<div class="mb-2">
<label for="thing1" class="form-label"
>Thing 1</label
>
<input
type="number"
class="form-control"
id="thing1"
name="thing1"
required
/>
</div>
<div class="mb-2">
<label for="thing2" class="form-label"
>Thing 2</label
>
<input
type="number"
class="form-control"
id="thing2"
name="thing2"
required
/>
</div>
<div class="form-group-row mb-3">
<button id="submitThings" type="submit" class="btn btn-primary">
Submit Things
</button>
</div>
</form>

我试过使用enctype="application/json" text/html"one_answers"application/x- ww-form-urlencoded",它们仍然返回一个空对象在request .body

这是我的post request:

form = document.getElementById("myForm");
form.addEventListener("submit", async (event, arg) => {
event.preventDefault();
console.log(event.target.action);
console.log(event.target);
let data = new FormData(event.target);
console.log(data.toString());
fetch(event.target.action, {
method: "post",
body: new FormData(event.target),
})
.then((res) => {
console.log(res.status);
return res.text();
})
.then((data) => {
console.log(data);
});
});

这是我的服务器端处理post请求- console.log工作,只显示一个空对象:

const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;
const app = express();
app.use(express.static(path.join(__dirname)));
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.post("/submit-thing1and2", async (req, res) => {
console.log("req.body", req.body);
res.send(req.body);
});
app.get("/", (req, res) => {
res.sendFile("./html/index.html", { root: __dirname });
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));

使用multer解析multipart/form-data请求:

app.post("/submit-thing1and2",
multer().fields([{name: "thing1"}, {name: "thing2"}]),
async function(req, res) {
...
});

最新更新