Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a token with an AJAX request from jQuery

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?

like image 848
larz Avatar asked Mar 08 '16 07:03

larz


People also ask

How can I pass Ajax token?

Your answer$. ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]'). attr('content') } }); Hope this is helpful!


1 Answers

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')} }); 
like image 80
gnerkus Avatar answered Sep 20 '22 00:09

gnerkus