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

2022-10-28前端开发问题
4

本文介绍了如何使用来自 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 请求发送令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End
ajax

相关推荐

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

Rails 3.1 ajax:成功处理
Rails 3.1 ajax:success handling(Rails 3.1 ajax:成功处理)...
2024-04-20 前端开发问题
11

使用 will_paginate gem 在 Rails 3.2.3 中调用 Ajax
Ajax call in rails 3.2.3 with will_paginate gem(使用 will_paginate gem 在 Rails 3.2.3 中调用 Ajax)...
2024-04-20 前端开发问题
6

使用视图附加或嵌入节点添加表单
Attach or embed node add form with a view(使用视图附加或嵌入节点添加表单)...
2024-04-19 前端开发问题
9

Drupal:如何使用 AJAX POST 从 REST 服务提交 webfrom
Drupal: How to submit the webfrom from REST services using AJAX POST(Drupal:如何使用 AJAX POST 从 REST 服务提交 webfrom)...
2024-04-19 前端开发问题
5