javascript - 这个路由这么写有什么问题?我想删掉一条记录
ringa_lee
ringa_lee 2017-04-17 16:35:04
0
2
404

我在roomview.html页面上想要删掉一条显示出来的记录,roomview.html部分代码如下:

<h1>房间列表</h1>
<p>
    <a href="/roomview/addroom">增加</a>

</p>
<table>
    <thead>
    <tr>
        <th>_id</th>
        <th>roomName</th>
        <th>roomContent</th>
        <th>roomCreateUser</th>
        <th>roomImg</th>
        <th>roomCreateDate</th>
        <th>roomJoinPeos</th>
        <th>roomChat</th>
    </tr>
    </thead>
    <tbody>
    <% rooms.forEach(function( room ){ %>
    <tr>
        <td><%= room._id%></td>
        <td><%= room.roomName %></td>
        <td><%= room.roomContent %></td>
        <td><%= room.roomCreateUser %></td>
        <td><%= room.roomImg %></td>
        <td><%= room.roomCreateDate %></td>
        <td><%= room.roomJoinPeos %></td>
        <td><%= room.roomChat %></td>
        <td><a href="/roomview/delete?id=<%=room._id%>">删除房间</a> | <a href="/roomview/modifyroom?id=<%=room._id%>">更新房间信息</a></td>
    </tr>
    <% }); %>
    </tbody>

路由roomview.js对应删除部分代码如下:

router.get("/delete/:id",function(req,res){
    console.log(req.params.id);
    Room.findById(req.params.id,function(err,doc){
        if(!doc){
            return next(new NotFound("Doc not found"))
        }else{
            doc.remove(function(){
                res.redirect("/roomview");
            })
        }
    });
});

不过当我点击删除房间后页面却显示如下:

Cannot GET /roomview/delete
ringa_lee
ringa_lee

ringa_lee

reply all(2)
巴扎黑

Get id

/roomview/delete?id=<%=room._id%>
router.get("/delete", cb)    
req.query.id

/roomview/delete/<%=room._id%>
router.get("/delete/:id", cb)
req.params.id

soonfy

刘奇

@soonfy is the correct answer.

You declared in the route that the parameters are required in the form of path variable: /delete/:id, path variable的形式要求参数:/delete/:id

但在页面上却又用了query parameter的形式提供参数: /roomview/delete?id=<%=room._id%>

那肯定会出错,最直观的表现就是你遇到错误,即:压根没找到路由/roomview/delete对应的处理器,因为你的处理器指定的规则是/delete/:id,而非/delete

解决方案也简单,把页面里改成/roomview/delete/<%=room._id%>

But on the page, the parameters are provided in the form of query parameter: /roomview/delete?id=<%=room._id%>. 🎜 🎜That will definitely go wrong. The most intuitive manifestation is that you encounter an error, that is: the processor corresponding to the route /roomview/delete is not found at all, because the rule specified by your processor is /delete/:id, not /delete. 🎜 🎜The solution is also simple, just change the page to /roomview/delete/<%=room._id%> and it should be fine🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template