当我尝试使用 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>
这里的方法应该是什么?我尝试给予 post 和 get 但徒劳。
最佳答案
如果您检查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/