vendredi 20 septembre 2019

Ajax success and error handlers not working with nodejs

I'm trying to do a simple alert on my app when my node server successfully completes a task. But I think I'm checking it wrong and I don't know how to fix it.

I checked other posts and they seem to be doing the same thing I am.

My ajax code:

$.ajax({
        url: path,
        method: 'POST',
        dataType: 'JSON',
        data: items,
        success: function(response)
        {

            alert('Tweety Logs sent successfully.')
        },
        error: function(err)
        {

            alert('Tweety Logs not sent.')
        }
});

The function in my server:

function log(req,res)
{
  var breed = req.body.breed;
  var list = req.body.logs;
  try {
    fs.appendFileSync("Logs/log.dat", JSON.stringify(breed) + "logs:\r\n");
    for(let i = 0; i < list.length; i++)
    {
      fs.appendFileSync("Logs/log.dat", JSON.stringify(list[i])  + "\r\n");
      console.log('Added to Logs/log.dat - ' + JSON.stringify(list[i]));
    }
    res.sendStatus(200);
  }
  catch (err) {
    console.log('Error writing to the file: ' + err.message)
    res.sendStatus(500);
  }
}

The error bit of ajax gets called everytime even if it's successful. Any idea why?




Aucun commentaire:

Enregistrer un commentaire