56

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?

4 Answers 4

89

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": "Bearer " + localStorage.getItem('token')}
});
4
  • why you send token into headers? why not into data ??
    – famas23
    Commented Nov 5, 2017 at 22:05
  • 2
    @ahmedbhs I believe his trying to protect token somehow. Commented Dec 16, 2017 at 17:22
  • 41
    for a JWT header, this worked for me headers: { "Authorization": 'Bearer ' + token }
    – user326608
    Commented Jan 22, 2018 at 2:46
  • 2
    You should be very careful when exposing your JWT token, in Javascript like a variable. Definitely don't expose it in frontend developer.okta.com/blog/2018/06/20/…
    – TomTom
    Commented Jan 10, 2020 at 5:05
12

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

headers: {
    Authorization: 'Bearer '+token
}

,

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!");
  }
});
1
  • 2
    but the question was how to send the saved token with the request. not how to save the token after the request.
    – larz
    Commented Jan 7, 2020 at 14:38
0

You can also do it like this.

     $.ajax({
        type: 'get', // or any other method you want
        dataType: 'json', 
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        url: `your-endpoint`,
        success: (data, status, xhr) => {
            if (data.status) {
               //Do something
            } else {
                console.warn("AJax failed");
            }
        },
        error: (xhr, textStatus, errorMessage) => {
            console.log(xhr.responseJSON.message);
        }
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.