Nodejs - 使用ajax从boostrap表单更新用户密码

时间:2018-03-16 18:49:18

标签: jquery node.js ajax mongodb twitter-bootstrap

我试图让用户在不重新加载页面的情况下更新密码,但我一直收到POST /user?userid=something 404错误。谁能发现我做错了什么?感谢。

Bootstrap模式

       <form method="post">
            <div class="modal-body">
                    <div class="form-group">
                        <label for="password">New password</label>
                        <input type="password" class="form-control" name="password" id="password" placeholder="Password" onkeyup='checkPassword();' required>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">Confirm new password</label>
                        <input type="password" class="form-control" id="confirmPassword" placeholder="Re-enter your password" onkeyup='checkPassword();' required>
                        <span id='message'></span>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button id="submit" type="submit" class="btn btn-primary" disabled>Save changes</button>
            </div>
        </form>

ajax脚本

<script>
$(function(){
    $('#submit').on('submit', function(e){
        e.preventDefault();
        var new_password = $('#password').val();
        $.ajax({
            url: '/user',
            type: 'post',
            data: new_password,
            success: function(data){
                alert(data)
            }
        });
    });
});

index.js - 服务器端

router.post('/user'), function (req, res) {
    User.updateOne({ '_id' :  req.query.userid }, {$set: {password: createHash(req.body.password)} });
}

1 个答案:

答案 0 :(得分:1)

它不起作用的原因是因为你没有method : 'POST'你发送的数据也不是一个对象而是一个值。如果您想使用req.body.password,请将其发送为{password:"thepassword"}

同时在数据中传递用户ID,因为它不是GET

$(function(){
    $('#submit').on('submit', function(e){
        e.preventDefault();
        var data = {
            userid: "theUserId",
            password: $('#password').val()
        }

        $.ajax({
            url: '/user',
            method : 'POST'
            data: data,
            success: function(data){
                alert(data)
            }
        });
    });
});

并且在路线中你必须发回状态确定。

//you should use body-parser middleware for this

router.post('/user', function (req, res) {
    User.updateOne({ '_id' :  req.body.userid }, {$set: {password: createHash(req.body.password)} });
    //you have to inform the client what happened!
    res.status(200).send();
}