首页 > 解决方案 > 将前端放入 RESTful api

问题描述

我正在使用 node、express 和 mongo 制作一个带有 api 的简单网站,并带有一个用于前端的简单 edgejs。所有路线都在邮递员中工作(GET、POST、PUT、DELETE)。但是,HTML5 不支持 PUT 方法。这是一个例子。

索引.js

... 
app.put('/api/item/:id', function(req, res, next){
      About.findByIdAndUpdate({_id: req.params.id}, req.body)
      .then(function(){
        About.findOne({_id: req.params.id})
        .then(function(about){
          res.send(about)
        });
      }).catch(next)
    });

这在邮递员中工作正常。这是我最初的看法。

编辑项.edge

    ...
    <form 
     action="/api/item/{{item._id}}" 
      method="PUT"
      encType="multipart/form-data">
        <div class="form-group">
          <label for="title">Name</label>
          <input type="text" class="form-control" name="name" placeholder="Name">
        </div>
        <div class="form-group">
          <label for="description">Profession</label>
          <input type="text" class="form-control" name="profession" placeholder="Profession">
        </div>
        <div class="form-group">
          <label for="description">Description</label>
          <input type="text" class="form-control" name="description" placeholder="Description">
        </div>
        <div class="form-group">
          <label for="description">Email</label>
          <input type="text" class="form-control" name="footerEmail" placeholder="Email">
        </div>
        <div class="form-group">
          <label for="content">Footer Description</label>
          <textarea name="footerDescription" id="" class="form-control" rows="10" placeholder="Footer Description"></textarea>
        </div>
        <div class="form-group text-center">
            <button class="btn btn-primary">Edit Item</button>
          </div>
      </form>

我考虑将一个函数绑定到编辑按钮以删除前一个项目并使用更新的内容创建一个新项目,但这不是最佳实践,可以吗?这会改变 id,从我在 Postman 中看到的情况来看,正确的 PUT 不会改变 id。我删除和替换的想法会。

那么如何允许从前端编辑此项目?

标签: node.jsmongodbexpressedgejs

解决方案


推荐阅读