Подтвердить что ты не робот

Как отправить токен с запросом AJAX из jQuery

Я использую express-jwt и создаю свой токен через jQuery и сохраняю его в своем локальном хранилище с помощью:

$.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);
  }
});

У меня есть защищенный маршрут в моем бэкэнде, например:

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

Как я могу отправить токен из localStorage с заголовком запроса?

4b9b3361

Ответ 1

Вы можете установить заголовки в $. 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')}
});