【问题标题】:Posting to database from html form从 html 表单发布到数据库
【发布时间】:2020-06-20 01:58:37
【问题描述】:

我确定这是我缺少的一件简单的事情,但互联网似乎没有文档来做这个简单的事情。

我正在尝试从我的 HTML 中获取数据并将其发送到我的数据库。我有一段时间忘记将我的脚本标签添加到 HTML 中,但它正在工作并在它停止工作之前将两个测试发送到数据库并说我的验证失败(标题和博客都是必需的)。

我错过了什么?感谢您的帮助!

我的表格:

<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:

const form = document.getElementById("blog-form");
form.onsubmit = (e) => {
  e.preventDefault();
  console.log(e.target.value); // this is coming back undefined

};

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");
  }

【问题讨论】:

  • 我还要提一下,我的服务器上有一个 app.use("api", apiRoutes),所以路由是 api/blog

标签: html database forms mongoose


【解决方案1】:

通过从 HTML 中删除 "enctype="multipart/form-data" 并删除所有 JS 来使其正常工作

【讨论】:

    猜你喜欢
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多