user1452030
user1452030

Reputation: 1041

jQuery and Express - success and error getting mixed up

This is sort of a basic question, but it's been nagging me for a while and I couldn't find any matching questions from my searches so far. So, apologies if it's too simple or repeated.

I have an API route (Express based) and I'm calling this route using jQuery AJAX call. Here is a simple stub to demonstrate the setup

$.ajax({
  url: "http://localhost:3000/admin/items/" + itemId,
  type: "POST",
  dataType: "json",
  data: itemData,
  contentType: "application/json",
  success: function(result){alert(result);},
  error: function(xhr, ajaxOptions, thrownError){
    alert("Could not update item details. Please try again later. Error: " + xhr.statusText);
  }
});

From the server, I confirmed that the status code returned is 200 and here is the implementation:

collection.update({ _id : mongo.ObjectID(req.params.id) }, req.body, function(err, result) {
  if(err){
    console.log("Error is: " + err);
    res.status(500).send("Could not update item with id: " + req.params.id);
  }else {
    if(result.result.n != 1){
     res.status(500).send("Could not find item with id: " + req.params.id);
    }
    else{
      console.log("Update successful");
      res.status(200).send("Successfully updated item id: " + req.params.id);
    }
  }
});

The functionality works perfectly, but at the end of the call, the error function is getting called and the alert I'm getting is: "Could not update item details. Please try again later. Error: OK".I tried a simple res.send without explicitly setting the status code too, but somehow it invariably calls the error function. What am I missing?

Upvotes: 1

Views: 171

Answers (1)

BenShelton
BenShelton

Reputation: 911

Further to my comment above, the reason this is occurring is because the dataType is set to expect a JSON response but express isn't sending JSON. When jQuery tries to parse the response it's unable to and throws an error even though the response status is 200.

If you wanted to keep the response you were sending in the initial example, simply removing the dataType from the ajax request would be enough, jQuery is normally pretty clever in figuring out what is being returned.

If however you wanted to receive JSON data (as clarified in the comments) then replace your response code with something like the following:

res.status(200).json({
  message: 'Successfully updated item',
  data: doc // document returned by mongo
});

Remember to change the error responses too to JSON. Even though jQuery would go to the error block anyway it's for the wrong reasons (invalid JSON rather then the error code) Something like this:

res.status(500).json({
  message: 'Server error occurred'
});

Upvotes: 2

Related Questions