使用POST方法提交GET的表单

时间:2016-11-28 09:29:18

标签: html node.js express pug

这是我遇到的最奇怪的问题,这是视图(在玉中):

extends layout
block content
 h1 Edit chatroom!!
 form(method="POST")
      fieldset.form-group
          label(for="name") Name:
          input.form-control(name="name", type="text", placeholder="Enter a name" value="#{room.name}")
          small.text-muted Give your chatroom a meaningful name for people to refer to it.
      button.btn.btn-primary(type="submit") Save chatroom
      a.btn.btn-default(href="/admin/rooms") Cancel     

这是返回浏览器的页面源代码的表单源:

<form method="POST">
               <fieldset class="form-group"><label for="name">Name:</label><input name="name" type="text" placeholder="Enter a name" value="independents" class="form-control"><small class="text-muted">Give your chatroom a meaningful name for people to refer to it.</small></fieldset>
               <button type="submit" class="btn btn-primary">Save chatroom</button><a href="/admin/rooms" class="btn btn-default">Cancel        </a>
            </form>

当我按下“保存聊天室”按钮时,我在网页上收到此错误消息:

Cannot GET /admin/rooms/edit/

这个快递路由器应该提交表单提交

router.route('/rooms/edit/:id')
.all(function(req, res, next) {
    var roomid = req.params.id;
    var room = _.find(rooms, r => r.id == roomid);
    if (!room) {
        res.sendStatus(404);
        return;
    }
    res.locals.room = room;
    next();
}).get(function(req, res) {
    res.render('edit');
}).post(function(req, res) {
    res.locals.room.name = req.body.name;
    //res.redirect(req.baseUrl + '/rooms'); or we can also
    res.redirect('./'); // but this is not good because if we had http://localhost:3000/admin/rooms/add/ it will take us to /add
});

我写的this previous question中存在这个小型快递应用程序(两个js文件)的完整代码。

1 个答案:

答案 0 :(得分:1)

在你的路线定义中你有

if (!room) {
  res.sendStatus(404);
  return;
}

在您的代码中,您似乎没有向具有ID的网址提交任何请求,因此它就像您告诉它一样返回404.

除非您使用的是具有ID的网址。这个页面上的URL是什么样的?