javascriptnode.jsexpresstitanium-mobile

How to get server error message in client side Node.js


My server checks before saving data in the database. Then if server cannot save data into database, it sends an error message.

In my client side app, how can I get this error and display it?

This is my client side http request-

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();
                }


                };

this is my server side "POST" code

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)

         })
      }
  })

})

Solution

  • You have to send a correct HTTP-Status. In Express, you do this as a first argument to send, so:

    res.send(500, errorMessage) or in newer Version res.status(500).body(errorMessage).

    With every other status than 200, it should trigger your error-callback in the XHR-Request.