Search code examples
javascriptjqueryflaskfrontendmsg

jQuery Don't send msg.message


https://github.com/simpleblog-project/Simple-Blog/issues/1

$.ajax({
      method: "POST",
      url: "http://localhost:5000/auth/login",
      data: JSON.stringify({
        "name"     : id,
        "password" : password
      }),
      contentType: 'application/json'
    })
    .done(function(msg) {
      if (msg.access_token) {
        createCookie(msg.access_token);
        window.location.href = './Main.html';
      }
      else { 
        if(msg.message)
        {
          console.log(msg.message);
          alert(msg.message);
        }
      }
    });

this

else{
  if(msg.message)
    {
      console.log(msg.message);
      alert(msg.message);
    }
}

that is not working. log was jquery-3.3.1.min.js:2 POST http://localhost:5000/auth/login 400 (BAD REQUEST) this problem is related by app.py this part ▼

@app.route('/auth/login', methods=['POST'])
def login():
    data = request.json
    name = data['name']
    password = data['password']
    user = User.query.filter_by(name=name).first()
    if user is None or not User.verify_password(user, password):
        return {"message": "invalid username or password"}, 400

    return {
        'access_token': create_access_token(user.id, expires_delta=access_token_exdelta),
        'refresh_token': create_refresh_token(user.id, expires_delta=refresh_otken_exdelta)
    }

Solution

  • Open the browser to your page and put a breakpoint in the browser on the code, you can click on F12 to open the developer window click on console and navigate to the line. click on the line to add a breakpoint.(red bullet) For ex.

    The if statement would be a nice spot to put a breakpoint on. (javascript side) when in a breakpoint ( you see a blue line / redline) hovering on that spot when you hit it, and you can see which variables you have. and in console you can type "msg" and it would show you the current state of the msg object.

    also might want to add a error part to the ajax call, just to check if the ajax call itself went ok.

     $.ajax({
        method: "POST",
          url: "http://localhost:5000/auth/login",
          data: JSON.stringify({
            "name"     : id,
            "password" : password
          }),
          contentType: 'application/json',
        success: function (data, status, xhr) {
            console.log("Succes!" + data);
        },
        error: function (xhr) {
            console.log("Error happened" +xhr.status);
    
        }
    });
    
    

    Look at the documentation how the ajax call works: https://api.jquery.com/jQuery.ajax/

    and check if you get the object "msg" back from the server. Good luck :).