这是我来自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/