【问题标题】:Delete request on express using form is not working使用表单的快速删除请求不起作用
【发布时间】:2019-03-05 05:41:27
【问题描述】:

当我尝试使用 node.js 通过表单从数据库中删除数据并表示它不会删除任何数据时。据我所知,只有两种方法获取和发布。没有删除方法。

router.js 代码

router.delete('api/:id', (req, res, next) => {
const id = req.params.id;
pool.query(`delete from book WHERE id = ?`, id, (err, result) => {
    if (err) throw err;
        res.status(201).json({ msg: `Deleted`});
  });
});

表格代码:

<form action="/api" method="">
 <input type="number" name="id" placeholder="delete" /><br/>
</form>

这里的方法应该是什么?我试图给 postget 但徒劳无功。

【问题讨论】:

  • HTML 表单方法默认为 GET。另外,尽管您是如何编写路由的,但您还是在正文中而不是在 URL 中发送 id。所以你在做什么,而不是DELETE /api/idGET /api
  • @MadWard 那么我如何通过 url 发送 id 呢?
  • @RomonaMK 使用 POST 并访问 req.body.id,或使用 AJAX 发送自定义 DELETE 路由。
  • 请查看以下链接以获取解决方案 - stackoverflow.com/questions/9859287/…

标签: javascript html node.js express


【解决方案1】:

如果你检查MDN docs

method 浏览器用来提交表单的 HTTP 方法。 可能的值是:

post:对应HTTP POST方式;表单数据包含在表单正文中并发送到服务器。

get:对应HTTP GET方法;表单数据使用“?”附加到操作属性 URI作为分隔符,以及结果。

如果要发送删除则监听表单上的submit 事件,调用event.preventDefault() 停止默认操作,并向后端发出自己的请求,这是一种更典型的“现代”方式无论如何都要这样做,因为它不会导致页面刷新。

如果没有 :id 部分中的内容,您的路线也不会受到影响。

一种方法如下:

给你的表单一个类或找到引用它的方法

<form action="/api" method="post" id="test-form">
    <input type="number" name="id" placeholder="delete" /><br/>
</form>

在你的 JavaScript 中,找到一种方法来引用表单并阻止它提交:

const form = document.getElementById('test-form');
form.addEventListener('submit', async event => {
    event.preventDefault();     // This prevents the form from submitting using POST

    const idInput = form.querySelector('input[name="id"]');
    const id = idInput.value;

    const res = await fetch(`https://apiurl.com/api/${id}`, {
      method: 'DELETE',
    });
    const json = await res.json();

    console.log(json);
});

【讨论】:

    【解决方案2】:

    由于表单不支持删除方法,您可以阻止表单自动发送并使用 fetch api 或 jquery xhr 手动发送请求:

     <form action="/api" method="" id="deleteApi">
        <input type="number" name="id" placeholder="delete" /><br/>
        <input type="submit" value="Submit">
     </form>
    

    js代码:

      $('#deleteApi').submit(function(event){
        event.preventDefault();
       // send a DELETE request to the api here
    
         $.ajax({
            url: '/api',
            type: 'DELETE',
            //data: ....
         }).done(function(res) {
            alert( "success", res );
         }).fail(function(err) {
            alert( "error", err );
         })
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-26
      • 2019-08-28
      • 2021-12-04
      • 1970-01-01
      • 2014-09-07
      • 2015-12-08
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多