【问题标题】:Can't update user model in express?无法在 express 中更新用户模型?
【发布时间】:2014-06-16 06:29:21
【问题描述】:

我正在尝试执行 put 请求来更新用户模型,但我的路由器只是发送另一个 get 请求。

这是我的路由器

router.get('/update', isLoggedIn, function(req, res) {
  res.render('update.ejs', {
      user : req.user // get the user out of session and pass to template
    });
});

router.put('/update', function(req, res) {
  var username = req.body.username;
  var profile_type = req.body.prof_type;
  var pic = req.body.profile_pic;
  var aboutme = req.body.whoami;
  console.log(req.body.whoami);
  User.findById(req.params.id,function(err, userup){
    if (!userup)
      return next(new Error("Couldn't load user"));
    else {
      userup.username = username;
      userup.prof_type = profile_type;
      userup.profile_pic = pic;
      userup.whoami = aboutme;
      userup.save(function(err) {
        if (err)
          console.log('error on update');
        else
          console.log('successful update');
      });
    }
  });
    res.redirect('/profile');

});

这是我的 html 输入表单

<form action="/update" method="put">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" class="form-control" name="username">
                </div>
                <div class="form-group">
                <h2> Pick a type of profile</h2>
                    <input type="radio" class="form-control" name="prof_type" value="true">Tutor<br>
                    <input type="radio" class="form-control" name="prof_type" value="false">Student
                </div>
                <div class="form-group">
                    <label>Link to profile picture</label>
                    <input type="text" class="form-control" name="profilepic">
                </div>
                <div class="form-group">
                    <label>About me</label>
                    <textarea name="whoami" class="form-control">Enter text here </textarea>
                </div>

                <button type="submit" class="btn btn-warning btn-lg">Update</button>
            </form>

我也尝试将它们更改为 /update/:username,但是,在单击带有字段的更新按钮后,我得到了这个地址

http://localhost:3000/update?username=bob&prof_type=false&profilepic=bob&whoami=bob

不知道我为什么不更新模型,甚至不知道为什么它不放。非常感谢任何帮助,谢谢!

【问题讨论】:

    标签: node.js http express


    【解决方案1】:

    HTML 仅支持 GETPOST 请求。详情见specification

    method和formmethod内容属性为枚举属性 带有以下关键字和状态:

    关键字get,映射到状态GET,表示HTTP GET 方法。关键字 post,映射到状态 POST,表示 HTTP POST 方法。这些属性的无效值默认值为 GET 状态。方法属性的缺失值默认值为 也是 GET 状态。 (没有缺失值默认值 formmethod 属性。)

    您只能将PUT 方法用于ajax 请求。比如jQuery:

    $.ajax({
        url: '/update',
        type: 'PUT',
        success: function(result) {
            // Do something with the result
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2011-06-28
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      相关资源
      最近更新 更多