2016-05-02 105 views
1

我通過ajax將表單提交給節點js服務器,並期望有錯誤,但如果有錯誤,而不是向我顯示錯誤,我將重定向到一個全新的頁面錯誤。我已經使用res.send,res.json,res.writheHead()...但我總是重定向到一個新的頁面如何從Node.js中的ajax post返回錯誤消息

  $.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

'res.status(400)以.json({錯誤: 「定製」}) ;' – vkstack

回答

0

看起來你正在得到的錯誤被認爲是你的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}) 
     }) 
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); 
} 

Doc