【问题标题】:NodeJS (Express) - app.delete route not workingNodeJS (Express) - app.delete 路由不工作
【发布时间】:2018-12-15 04:21:04
【问题描述】:

通过设置从我的 HTML5 文档到 Postgres 数据库的简单路由来了解 CRUD 基础知识。我的 GET 和 POST 按钮正在工作,但我的 DELETE 没有从我的数据库中删除。我意识到这些路由看起来都非常相似(并尝试重命名它们以查看它是否会命中链接到数据库的回调函数,但它不起作用)。谁能告诉我为什么我的 HTML5 表单无法与我的路由一起到达数据库以进行删除?谢谢!

我将只包含我所指的代码,因为我的所有其他代码都运行良好。首先显示糟糕的 HTML,然后是 index.js 和路由,然后是 queries.js 和数据库查询。 ( ////// 将拉取代码的文档分开 :) )

 <h1>Let's DELETE ONE Human</h1>
    <form action="/users/:id" method="delete">
        ID:<input type="number" name="id">
        <input type="submit" name="">
    </form>

    /////////////////////////////////////////////////////////////////

    app.get('/', (request, response) => {
      response.sendFile(path.join(__dirname + '/html/homepage.html'))
    }, db.getUsers)

    app.get('/newHuman.html', (request, response) => {
      response.sendFile(path.join(__dirname + '/html/newHuman.html'))
    })
    app.get('/users', db.getUsers)
    app.get('/users/:id', db.getUserById)
    app.post('/users', db.createUser)
    app.put('/users/:id', db.updateUser)
    app.delete('/users/:id', db.deleteUser)

    app.listen(port, () => {
      console.log(`App running on port ${port}.`)
    })
  ////////////////////////////////////////////////////////////////////////

const deleteUser = (request, response) => {
      const id = parseInt(request.query.id)

      pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
        if (error) {
          throw error
        }
        response.status(200).send(`User deleted with ID: ${id}`)
      })
    }

TL;DR
当 app.delete 和 app.put 具有完全相同的路由时,如何从我的 HTML 发送到正确的路由(即使只发布两次)?尝试重命名路线,没有用,但我知道你不应该重命名它才能工作。以下是路线:

app.put('/users/:id', db.updateUser) app.delete('/users/:id', db.deleteUser)

【问题讨论】:

  • 您不能在 HTML5 表单上使用 delete,因为它们正式不是表单标准的一部分。考虑使用 POST 作为隧道,即在内部将发布操作重定向到服务器端的删除操作。更多详情请见softwareengineering.stackexchange.com/questions/114156/…
  • 嗨小腿!感谢您的精彩回复。但是,如果我将 POST 用于 DELETE 和 PUT 方法,我将如何在不更改路由名称的情况下指定路由?如您所见,POST 会很好,但 put 和 delete 具有相同的路由名称。 app.post('/users', db.createUser) app.put('/users/:id', db.updateUser) app.delete('/users/:id', db.deleteUser) 有什么想法吗?谢谢!

标签: node.js html postgresql express crud


【解决方案1】:

HTML 表单方法仅支持GETPOST 方法。

您必须使用GETPOST 或使用ajax 或诸如requestaxios 之类的库来发出删除请求。

例如,如果您使用 axios,请尝试以下代码。

如果您已经导入了jQueryaxios,请忽略它们。

<!-- import jQuery -->
<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>
<!-- import axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<h1>Let's DELETE ONE Human</h1>
<form id='myFormId' action="/users/:id" method="delete">
    ID:<input type="number" name="id" id='deleteId'>
    <input type="submit" name="">
</form>


<script>
    $( document ).ready(function() {
        const myForm = $('#myFormId');
        myForm.submit((event) => {
            event.preventDefault();
            const id = $('#deleteId').val();
            const url = `/users/${id}`;
            axios.delete(url)
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    });
</script>

【讨论】:

  • 当我使用 GET 和/或 POST 时,问题与将 DELETE 作为 html 方法相同。它命中了 '/users/:id' 的 app.get 路由,因为它与 app.delete 的路由相同。如何指定路线?我尝试更改路线名称,但没有成功。
  • 我使用 axios 库通过删除请求的示例更新了答案。请检查一下。
【解决方案2】:

另一种更简单的方法是使用名为 method-override 的 npm 模块。

在您的服务器的主入口点文件中,添加以下行:

const express = require('express');
const app = express();
const methodOverride = require('method-override');
app.use(methodOverride('_method'));

在您的 HTML 表单中,您现在可以轻松地使用 PUT 或 DELETE 请求: 例如:

    <h1>Let's DELETE ONE Human</h1>
<form id='myFormId' action="/users/:id?_method=DELETE" method="delete">
    ID:<input type="number" name="id" id='deleteId'>
    <input type="submit" name="">
</form>

注意表单的 action 属性,你现在要做的就是添加简单的一行就完成了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多