如何在jQuery的不同AJAX请求中传递Bearer Token?
问题分析与修复方案
核心错误点
Authorization请求头拼接错误
你在地址验证API的请求头里写了:authorization: "'Bearer '+ getToken"这会把字符串
'Bearer '+ getToken直接作为Authorization头的值发送,而不是把getToken变量的实际值拼接进去。同时多余的单引号也会破坏Bearer认证的格式规范。Token存储冗余处理
你用JSON.stringify(token)存储token,但token本身就是字符串类型,没必要做JSON序列化,直接存储原始字符串即可,取用时也无需额外解析。请求体格式不匹配
FedEx地址验证API要求请求体为JSON格式,但你的代码直接传入JS对象,jQuery默认会将其转换为application/x-www-form-urlencoded格式,这会导致API无法正确解析请求内容(虽然这不是401错误的直接原因,但会引发后续请求失败)。
修正后的代码
获取Token的请求(优化存储逻辑)
$("#btnStartDiscount").click(function () { $.ajax({ async: true, crossDomain: true, url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/oauth/token", method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", }, data: { grant_type: "client_credentials", client_id: "xxxxxxxxxxx", client_secret: "xxxxxxxxxxxxx", }, success: function (response) { console.log(response); const token = response.access_token; console.log(token); enterAddressFields(); document.FedExShip.tokenField.value = token; // 直接存储字符串,无需JSON序列化 sessionStorage.setItem("myToken", token); const getToken = sessionStorage.getItem("myToken"); console.log(getToken); alert("Connected Token " + getToken); }, error: function (error) { console.log(JSON.stringify(error)); }, }); });
地址验证API请求(修复头和请求体)
$("#btnAddrValidate").click(function () { const getToken = sessionStorage.getItem("myToken"); $.ajax({ url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/address/v1/addresses/resolve", method: "POST", headers: { // 正确拼接Bearer token,去掉多余单引号,注意Bearer与token间的空格 authorization: `Bearer ${getToken}`, "x-locale": "en_US", // 指定请求体为JSON格式 "content-type": "application/json" }, // 将JS对象转为JSON字符串,匹配API要求的格式 data: JSON.stringify({ addressesToValidate: [ { address: { streetLines: ["7372 PARKRIDGE BLVD", "APT 286"], city: "IRVING", stateOrProvinceCode: "TX", postalCode: "75063-8659", countryCode: "US", }, }, ], }), success: function (response) { console.log(response); console.log(getToken); alert("Successfully passed token " + getToken); alert("Success"); }, error: function (error) { console.log(JSON.stringify(error)); alert("Failed to pass token " + getToken); }, }); });
内容的提问来源于stack exchange,提问作者mGeek
相关产品推荐
相关产品推荐

