如何使用来自 jQuery 的 AJAX 请求发送令牌

时间:2022-10-28
本文介绍了如何使用来自 jQuery 的 AJAX 请求发送令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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?

解决方案

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')}
});

这篇关于如何使用来自 jQuery 的 AJAX 请求发送令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:在 node.js 中更改密码和注销时使 JWT 无效的最佳实践? 下一条:Auth0中的id_token和access_token有什么区别

相关文章

最新文章