我通过ajax向节点js服务器提交一个表单,如果有的话会出现错误,但不是向我显示错误,而是重定向到一个包含错误的新页面。我使用了res.send,res.json,res.writheHead()...但我总是重定向到新页面
$.ajax({
url: $this.attr('/api/adduser'),
type: $this.attr('POST'),
data: $this.serialize(),
dataType: 'json', // JSON
success: function(json) {
alert('Erreur : '+ json.reponse);
}
})
event.preventDefault()
在服务器端我有:
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
答案 0 :(得分:1)
您的错误似乎被认为是来自您的sql承诺的成功响应。要解决这个问题,比如
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
// look into your result to see if you have what you asked for
if(result.error) {
res.status(500).send({error: 'you have an error'});
}
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
答案 1 :(得分:0)
一种选择是使用ajax错误:
success: function (json) {
alert(json);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}