Is the error coming from the ajax call or the server?

Is the error coming from the ajax call or the server?
0

#1

Ok, I have this code on the server side:

//login
app.post('/api/users/login',function(req,res){
  User.findOne({email:req.body.email}).then(function(user){
    if(!user){
      return res.status(400).send('email invalid')
    }
    bcrypt.compare(req.body.password, user.password, function(err,response){
      if (response){
        user.generateAuthToken().then(function(token){
          // this works. I can get that far in the code
          res.header('x-auth',token).send(response);
        })
      } else {
        return res.status(400).send('wrong password')
      }
    })
  }).catch(function(e){
    res.status(400).send(e);
  })
});

and this on the front-end:

var submitLogin = function(){
  var body = {
    email: document.getElementById('login-email').value,
    password: document.getElementById('login-password').value
  };

  $.ajax({
    type : "POST",
    url : "/api/users/login",
    data : body,
    dataType: 'json',
    success: function(){
      console.log('success')
    },
    error: function(error) {
      // the front-end keeps running this error function instead of the success function.
      console.log('error: '+error)
    }
  });
}

can anyone figure out why the success function never runs?

edit to add: the call works in postman and returns the ‘response’ object and a 200 status


#2

Does the error object describe the problem or provide any other information at all?


#3

{readyState: 0, responseText: “”, status: 0, statusText: “error”}

that is coming from the error function in the front-end


#4

From what I have gathered so far, it’s a problem with data format.
I added to the ajax call: contentType: 'application/json" and it changed the error message. I now get a 400 error: ‘unexpected token e’

Obviously I am still a bit unsure about how data types are sorted in the front-end / back-end communication. And all I was in all cases is JSON. That should be simple.

edit to add: I now also change the data to: JSON.Stringify(body) and I am back to getting an empty error response back from the server.

Obviously I am just going by trial and error now and it won’t get me very far. If anyone knows some good resources to read about how to do ajax requests sending JSON data, let me know.