How to send a token with an AJAX request from jQuery

前端 未结 3 832
滥情空心
滥情空心 2020-12-13 04:01

I use express-jwt and create my token via jQuery and save it in my localStorage with:

$.ajax({
  url: \"http://localhost:8080/login\",
  type: \'POST\',
  d         


        
3条回答
  •  生来不讨喜
    2020-12-13 04:45

    I use the approach below to cover JWT authentication with the result status types

    $.ajax({
      url: "http://localhost:8080/login",
      type: "POST",
      headers: { Authorization: $`Bearer ${localStorage.getItem("token")}` },
      data: formData,
      error: function(err) {
        switch (err.status) {
          case "400":
            // bad request
            break;
          case "401":
            // unauthorized
            break;
          case "403":
            // forbidden
            break;
          default:
            //Something bad happened
            break;
        }
      },
      success: function(data) {
        console.log("Success!");
      }
    });
    

提交回复
热议问题