<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery调用token</title> <script src="../js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script> <script src="js/com.ibaiqi.public.js" type="text/javascript" charset="utf-8"></script> </head> <body> <ul> <li><input type="button" id="btn2" onclick="loginCheck()" value="登陆查看控制台" /></li> <li><input type="button" id="btn2" onclick="userList()" value="查看是否授权登陆" /></li> <li><input type="button" id="btn2" onclick="getBaidu()" value="查看是否授权登陆baidu.com" /></li> </ul> </body> </html> <script type="text/javascript"> $.ajaxSetup({ beforeSend: function(xhr) { // 发送请求时,带上token xhr.setRequestHeader("token", localStorage.getItem("token")) }, error: function(xhr,status,error) { console.log(xhr); if (xhr.status === 401) { console.log("跳转到登陆页面") window.location.href = "./login.html" } } }); /* 登陆与不登陆,返回不同json */ function userList() { console.log("userlist 准备请求111"); console.log(url); //读取本地存储token // var token=localStorage.getItem("token") $.ajax({ url: baseUrl+"/api/user/list", // url: "http://169.254.150.246/api/user/list", method: "get", /* headers: { "token": token }, */ success: function(res) { console.log(res); } }) } /* 登陆成功,返回token 到控制台 */ function loginCheck() { var token = localStorage.getItem("token") $.post( "http://169.254.150.246/jwt/login?username=admin&password=admin123", function(res) { console.log(res); //把反回过来token写入本地存储 localStorage.setItem("token", res.token) } ) } /* 请求百度 */ function getBaidu() { console.log("getBaidu.com 准备请求"); $.get( "https://www.baidu.com/", null, function(res) { console.log(res); } ) } </script>