[英]How to get server error message in client side Node.js
我的服務器在將數據保存到數據庫之前進行檢查。 然后,如果服務器無法將數據保存到數據庫中,它將發送一條錯誤消息。
在我的客戶端應用程序中,如何獲取此錯誤並進行顯示?
這是我的客戶端HTTP請求-
button.addEventListener('click', function(e) {
var service_ = service.value;
if (start_pick < end_pick) {
var jsondata = [{
start_time : new Date(start_pick),
end_time : new Date(end_pick),
service : service_,
}];
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(10000);
xhr.open("POST", "url");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(jsondata));
xhr.onerror = function(e) {
//Ti.API.debug(e.error);
// console.log(e.error)
Titanium.API.info("Error in connecting to server !!");
alert("Error in connecting to server !!");
};
xhr.onload = function(e) {
//alert(e)
if (e.error) {
alert(this.responseText);
} else {
windowAddDataInvoce.close();
}
};
這是我的服務器端“ POST”代碼
app.post('/collections/:collectionName', function(req, res, next) {
console.log(req.body[0])
req.collection.findOne({"service":req.body[0].service}, function(e, result){
if(result){
console.log(result); console.log(e)
res.send({error:"Task already exits"})
}
else{
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
})
}
})
})
您必須發送正確的HTTP狀態。 在Express中,您將此操作作為要發送的第一個參數,因此:
res.send(500, errorMessage)
或更高版本中res.status(500).body(errorMessage)
。
除200以外的其他所有狀態,它都應在XHR-Request中觸發您的錯誤回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.