管理用户与Express应用程序的交互

时间:2021-10-03 12:59:16

I am fairly new to Express. In this case I have a <table> in the page users in which I have one link in each row to delete the entry. Every time the user click on these links I have to delete that entry in the database. This is not a SPA and I do not (want to) use other front end frameworks like React.

我对Express很新。在这种情况下,我在页面用户中有一个

,我在每行中都有一个链接来删除该条目。每次用户单击这些链接时,我都必须删除数据库中的该条目。这不是SPA,我不(想)使用像React这样的其他前端框架。

What is the best way to deal with this?

处理这个问题的最佳方法是什么?

The way I was dealing with it was creating a new route:

我处理它的方式是创建一条新路线:

router.get('/users/delete/:userId', db.deleteUser(req.query.deleteUser));

And the in the front end at the end of every row:

并且在每行末尾的前端:

<a href="users/delete/deleteuser=77">Delete this user</a>

But it does not seem the best way to go about this. I thought about using AJAX but I found it a bit of a overhead to create a hidden input and a for for each row of my table. Many thanks.

但这似乎不是解决这个问题的最好方法。我想过使用AJAX但我发现创建隐藏输入和for表格的每一行都有点开销。非常感谢。

1 个解决方案

#1


0  

You can delete in router like below

您可以在路由器中删除如下所示

Server-side

router.delete('/users/:userId(\\d+)', deleteUser);
... 
function deleteUser(req, res, next) {
    db.deleteUser(req.params.userId, function(err) {
        if (err)
            return res.status(500).send(err.message);

        res.status(200).end(); 
    });
}   

Client-side

<a onclick="deleteUser(77)">Delete this user</a>
...
function deleteUser(id) {
    $.ajax({
        type: 'DELETE',
        url: '/users/' + id,
        success: function(data) {
            window.location.href = '/users';
        }
    });
}

#1


0  

You can delete in router like below

您可以在路由器中删除如下所示

Server-side

router.delete('/users/:userId(\\d+)', deleteUser);
... 
function deleteUser(req, res, next) {
    db.deleteUser(req.params.userId, function(err) {
        if (err)
            return res.status(500).send(err.message);

        res.status(200).end(); 
    });
}   

Client-side

<a onclick="deleteUser(77)">Delete this user</a>
...
function deleteUser(id) {
    $.ajax({
        type: 'DELETE',
        url: '/users/' + id,
        success: function(data) {
            window.location.href = '/users';
        }
    });
}