52

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',
  data: formData,
  error : function(err) {
    console.log('Error!', err)
  },
  success: function(data) {
    console.log('Success!')
    localStorage.setItem('token', data.id_token);
  }
});

I have a protected route in my backend like:

app.get('/upload',jwt({secret: config.secret}), function(req, res) {
  res.sendFile(path.join(__dirname + '/upload.html'));
});

How can I send the token from localStorage with the request header?

gnerkus
  • 11,357
  • 6
  • 47
  • 71
larz
  • 813
  • 1
  • 12
  • 29

3 Answers3

83

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')}
});
gnerkus
  • 11,357
  • 6
  • 47
  • 71
10

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

headers: {
    Authorization: 'Bearer '+token
}

,

yogihosting
  • 5,494
  • 8
  • 47
  • 80
5

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!");
  }
});
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
  • 2
    but the question was how to send the saved token with the request. not how to save the token after the request. – larz Jan 07 '20 at 14:38