Reputation: 1247
I have a simple multi-page app written in vanilla JS, Pug, and Node, that uses login with JWT. When a user signs in, the client is returned a JWT. The JWT is stored in localStorage
. Here is my clientside ajax request for when a user logs in and is returned a token:
$.ajax({
url: "/login",
type: "POST",
data: { arr },
success: (res) => {
if (res.status == 200) {
localStorage.setItem("token", res.token);
console.log("success");
}
},
error: (err) => { console.log(err) }
});
The above works fine.
Each page on the site has a number of different links or buttons: /home
, /profile
, /about
, etc. Some of the routes are protected (only for logged in users), which is why I'm using JWT in the first place. I've seen on YouTube tutorials that the JWT should be stored in localStorage
and sent in requests in the header. I believe I already have serverside middleware that will successfully check if a valid JWT is in the header. My question is this: How do I add the JWT to the request header when a user clicks a link on my page, so I can then do the verification serverside? Is this possible given that I'm using vanilla JS or do I need a different solution?
Here is a typical page for my site (written in Pug).
body
h1 History of changes
div View previous changes
br
each val, ind in histArr
div.history
a(href="/diff/" + val.numb)
button See changes
span= " " + val.date + " " + val.author + " " + val.message
br
a(href="/history")
button /history
a(href="/")
button home
a(href="/profile")
button profile
How do I add the JWT to the header for when a user clicks on these buttons?
EDIT
For example: A user is on my site's home page. They click on a link that is a protected route. I want to check if they are logged in (i.e., have a JWT) before rendering the page. How do I add the JWT to the request header to check that? More specifically, is using an ajax call the only way to add my JWT to the request header or is there another way?
Upvotes: 0
Views: 2315
Reputation: 4533
Pass header from Ajax
in this way ...
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("token", {{{token}}); // Set dynamic token
},
url: "/login",
...
});
Another way :
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization': {{token}},
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
View this link
update
Please check this link to pass header in vanilla js.
var httpHandler = function (err, str, contentType) {
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('An error has occured: ' + err.message);
} else {
res.writeHead(200, {'Content-Type': contentType});
res.end(str);
}
};
Now you can try to set near at writeHear
.
Upvotes: 2
Reputation: 3455
You can set headers like this:
$.ajax({
url: 'ajax_url',
...
headers: {
'Authorization': 'Bearer ' + 'your_token'
}
})
Upvotes: 0