How to send a token with an AJAX request from jQuery
If you are using JWT authentication then this is how you add it to the headers in .ajax() method:
headers: {
Authorization: 'Bearer '+token
}
,
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')}
});
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!");
}
});