最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to redirect button in express using specific mongodb

网站源码admin29浏览0评论

How to redirect button in express using specific mongodb

How to redirect button in express using specific mongodb

我正在尝试使用

_id
字段更新我在 MongoDB 中的数据,这是执行此操作的 HTML 按钮:

<form action="/update/:_id" method="get" id="edit-button">
  <button class="btn btn-success" type="submit" id="edit-button">
    Edit Post
  </button>
</form>

这是我的 Express 服务器的代码

app.js

app.get('/update/:_id', function (req, res) {
  const updateId = req.params._id;
  Post.findOne({ _id: updateId })
    .then((Posts) => {
      res.render('update', {
        updatedTitle: Posts.title,
        updatedContent: Posts.content,
        id: updateId,
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

app.post('/update', function (req, res) {
  // const updateId = req.params.updateId;
  const updatedTitle = req.body.updatedTitle;
  const updatedContent = req.body.updatedContent;
  const updateId = req.body.id;

  post
    .findByIdAndUpdate(
      { _id: updateId },
      {
        title: updatedTitle,
        content: updatedContent,
      }
    )
    .then(() => res.redirect('/'));
});

这是我的视图模板的代码

update.ejs

<form action="/update" method="get">
  <div class="mb-3">
    <label for="titleInput" class="form-label">Title</label>
    <input
      type="text"
      class="form-control"
      name="updatedTitle"
      value="<%= updatedTitle %>"
      required
    />
  </div>
  <div class="mb-3">
    <label for="postArea" class="form-label">Post</label>
    <textarea
      class="form-control"
      rows="5"
      name="updatedPost"
      value="<%= updatedContent %>"
      required
    ><%= updatedContent %></textarea>
  </div>
  <button
    class="btn btn-primary update"
    type="submit"
    name="id"
    value="<%= id %>"
  >
    Update
  </button>
</form>

当我尝试直接访问链接时,它工作正常。例如:

http://localhost:3000/update/644a6d4c6fbe854da2375c61
。但是,当我尝试按下按钮或摆弄代码时,它会出现以下错误之一:

无法获取/更新

或在控制台中:

CastError: Cast to ObjectId failed for value ":_id" (type string) at
path "_id" for model "Post" and BSONError: Argument passed in must be
a string of 12 bytes or a string of 24 hex characters or an integer
回答如下:

你可以简单地给按钮添加一个事件监听器并处理点击事件:

<script>
  const editButton = document.getElementById('edit-button');
  editButton.addEventListener('click', () => {
    fetch(`http://localhost:3000/update/${whatever-the-id}`)
      .catch(error => console.log(error));
  })
</script>


<button class="btn btn-success" type="button" id="edit-button">
  Edit Post
</button>
发布评论

评论列表(0)

  1. 暂无评论