How to send a token with an AJAX request from jQuery

前端 未结 3 826
滥情空心
滥情空心 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!");
      }
    });
    
    0 讨论(0)
  • 2020-12-13 04:50

    You can set the headers in a $.ajax request:

    $.ajax({
      url: "http://localhost:8080/login",
      type: 'GET',
      // Fetch the stored token from localStorage and set in the header
      headers: {"Authorization": localStorage.getItem('token')}
    });
    
    0 讨论(0)
  • 2020-12-13 04:53

    If you are using JWT authentication then this is how you add it to the headers in .ajax() method:

    headers: {
        Authorization: 'Bearer '+token
    }
    

    ,

    0 讨论(0)
提交回复
热议问题