javascript - 使用表单删除 express 请求不起作用

标签 javascript html node.js express

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

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 但徒劳。

最佳答案

如果您检查MDN docs :

method The HTTP method that the browser uses to submit the form. Possible values are:

post: Corresponds to the HTTP POST method ; form data are included in the body of the form and sent to the server.

get: Corresponds to the HTTP GET method; form data are appended to the action attribute URI with a '?' as separator, and the resulting.

如果您想发送删除,请监听表单上的 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);
});

关于javascript - 使用表单删除 express 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54921871/

相关文章:

javascript - Chrome 扩展选项卡 onUpdated 事件

javascript - 使用正则表达式替换 innerHTML 文本时的性能问题

html - CSS Bootstrap Row Flex 和显示问题

javascript - 在 puppeteer 中将屏幕截图转换为 pdf

javascript - 如何在 Node js 和 mongodb 中获取当前保存的文档 _id?

javascript - Google map 信息窗口表单内容显示在 map 下方

javascript - 在发布/订阅中使用 session.get 变量

javascript - Eyecom 的 Bootstrap 日期选择器似乎不起作用?

html - Angular 5 在显示 mat-sidenav-container 时停止背景滚动

node.js - Mongoose 和新架构 : returns "ReferenceError: Schema is not defined"