javascript - 当没有找到记录时,我需要向用户发送警报

标签 javascript jquery node.js

这是我来自nodejs服务器的post请求

app.post('/api/users', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(req.body);
    var data = req.body;
    db.collection('users').findOne({
        username: data.username
    }, (err, result) => {
        if (result === null) {
            db.collection('users').insertOne(data, function (err) {
                if (err) throw err;
                console.log("Record inserted!");
                res.status(200).send("recordInserted");
            })
        } else {
            console.log("Already exists");

            res.status(500).send("userExists");
        }
    })

})

这是我的ajax请求

$('#signupForm').on('submit', function () {
    var userData = {
        fullName: $("#fullName").val(),
        username: $("#username").val(),
        password: $("#password").val(),
        email: $("#email").val()
    };
    $.ajax({
        type: "post",
        data: userData,
        dataType: "text",
        url: "/api/users",  
        function (data, status) { 
            if(data== 'recordInserted'){
                alert("Recors inserted");
                console.log("Inserted \n" + data +"\n" + status);
            }
            else if(data == 'userExists') {
                alert("User exists");
                console.log(data + "\n " + status);

            }
         }
    });


});

我无法发回对 ajax 请求的响应,因此如果用户已存在,页面不会重新加载或显示错误

最佳答案

作为首要任务,目前处理 AJAX 响应的首选方法是利用延迟对象。

let request = $.ajax({url: 'google.com', type:'get'});

request.done(function(response){
 // handle response
});

除此之外,您的后端看起来还不错。

虽然!

我强烈建议更改服务器端错误处理的方式。如果服务器抛出错误,客户端将处于挂起状态,直到超时。最好也提醒客户端发生了错误。

关于javascript - 当没有找到记录时,我需要向用户发送警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59190024/

相关文章:

javascript - 如何在 OpenCart 中延迟或异步 javascript

javascript - 通过数组查找项目

javascript - Jade 中的过滤器嵌套失败

node.js - 使用 node.js 检测 html 按钮单击?

javascript - 我如何引用 eq() jquery 的 child

javascript - 检索字段时出错,javascript minifier 错误

javascript - 更改状态栏中的链接

javascript - 轻量级 jQuery 树 Controller ?

javascript - 调用父对象函数

node.js - Jimp 读取 Url => 错误 : unable to verify the first certificate in nodejs