[英]Posting to database from html form
I'm sure this is a simple thing I am missing but the internet seems devoid of the documentation to do this simple thing.我确定这是我缺少的一件简单的事情,但互联网似乎没有文档来做这个简单的事情。
I am trying to grab data from my HTML and send it to my database.我正在尝试从我的 HTML 中获取数据并将其发送到我的数据库。 I forgot to add my script tag to the HTML for a while but it was working and sent two tests into the database before it stopped working and said my validations failed (both title and blog are required).
我忘记将我的脚本标签添加到 HTML 有一段时间了,但它正在工作并在停止工作之前将两个测试发送到数据库并说我的验证失败(标题和博客都是必需的)。
What am I missing?我错过了什么? Thank you for your help!
谢谢您的帮助!
my form:我的表格:
<form
action="/api/blog"
method="POST"
id="blog-form"
class="blog-form container mt-5"
enctype="multipart/form-data">
<label for="title">Title</label>
<input type="text" name="title" />
<br />
<label for="blog">Text</label>
<textarea name="blog" rows="15" cols="120"></textarea>
<input type="submit" value="submit" />
</form>
JS: JS:
const form = document.getElementById("blog-form");
form.onsubmit = (e) => {
e.preventDefault();
console.log(e.target.value); // this is coming back undefined
};
API route: API 路线:
router.post("/blog", async (req, res) => {
console.log(req.body);
const blog = new Blog({
title: req.body.title,
blog: req.body.blog,
});
try {
await blog.save();
res.status(201).json(req.body);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
got it working by removing the "enctype="multipart/form-data" from the HTML and removing all of the JS通过从 HTML 中删除 "enctype="multipart/form-data" 并删除所有 JS 使其工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.