Js代码:
// 封装一个函数,用于发起带有 Authorization 头部的 Ajax 请求
function ajaxWithAuth(options) {
// 获取用户的 token,从浏览器本地存储中
var token = localStorage.getItem('access_token');
// 扩展传入的选项对象,添加 headers 和 error 处理
var defaultOptions = {
headers: {
'Authorization': 'Bearer ' + token
},
error: function (xhr, status) {
console.error('XHR Object:', xhr);
console.error('Status:', status);
if (xhr.status === 405) {
console.log("无效的请求方式");
} else if (xhr.status === 404) {
console.log("未找到URL资源");
} else if (xhr.status === 500) {
console.log("服务器内部错误,请联系管理员");
} else {
console.log("产生异常,请联系管理员");
}
// 如果请求失败,跳转到指定的失败页面
window.location.href = 'failure.html';
}
};
// 合并默认选项和用户传入的选项
var ajaxOptions = $.extend(true, {}, defaultOptions, options);
// 发起 Ajax 请求
$.ajax(ajaxOptions);
}
// 使用封装的 ajaxWithAuth 方法发起请求
ajaxWithAuth({
url: 'http://localhost:8089/report/revenue/testList',
type: 'GET',
data: { etlDate: '20240514' },
dataType: 'json',
success: function (res) {
if (res.code === '200') {
// 返回成功的处理逻辑
console.log("请求成功");
// 第一次登录保存access_token在浏览器
localStorage.setItem('access_token', 'bf2we2fnl2kwv452dv23d13v23sd4v')
}
}
});
Java代码:
@RequestMapping(path = "/testList")
public Object testList(@RequestParam String etlDate, @RequestHeader(value = "Authorization") String token) {
System.out.println("etlDate: " + etlDate);
System.out.println("------------------------");
System.out.println("Authorization: " + token);
return new WebResponse(ErrorCode.SUCCESS, etlDate + ": " +token);
}