HTML中调用后端Ajax接口返回401未授权错误如何解决
问题解决办法
你当前代码中直接将apikey作为$.ajax的顶层配置项,jQuery Ajax并不会识别该字段并将其传递到服务端,导致服务端无法拿到身份校验信息返回401。你在Insomnia中是将apikey放在请求头或者查询参数中传递,和前端写法不一致才会出现调用结果不同的情况。
两种常见的修改方案
方案1:apikey通过请求头传递(最常见)
如果Insomnia中你是将apikey放在请求头中传递,修改AJAX配置,增加headers字段存放校验信息:
$.ajax({ url: "https://ecoexchange.dscloud.me:8080/api/get", method: "GET", // 新增headers配置,把apikey放到请求头中 headers: { apikey: sessionStorage.getItem("apikey") // 如果服务端要求Bearer格式,替换为下面的写法 // "Authorization": "Bearer " + sessionStorage.getItem("apikey") }, dataType: 'json', success: function(result) { $('#infoTable tr').empty(); var header = $('#infoTable thead'); var body = $('#infoTable tbody'); var hTr; $('#infoTable thead').append(hTr = $('<tr>')); // Headers for (var h = 0; h < result.headers.length; h++) { hTr.append($('<th>', { text: result.headers[h] })) } // Body for (var d in result.data) { var data = result.data[d]; $('#infoTable tbody').append($('<tr>') .append($('<td>', { text: data.RecyclableID })) .append($('<td>', { text: data.Name })) .append($('<td>', { text: data.RecyclableType })) ) } }, // 新增错误回调方便排查问题 error: function(xhr, status, error) { console.log('请求错误信息:', xhr.responseText); console.log('当前传递的apikey:', sessionStorage.getItem("apikey")); } })
方案2:apikey通过GET查询参数传递
如果Insomnia中你是将apikey作为URL后的查询参数传递,修改AJAX配置的data字段传递参数:
$.ajax({ url: "https://ecoexchange.dscloud.me:8080/api/get", method: "GET", // 把apikey放到GET请求的查询参数中 data: { apikey: sessionStorage.getItem("apikey") }, dataType: 'json', success: function(result) { // 原有逻辑不变 $('#infoTable tr').empty(); var header = $('#infoTable thead'); var body = $('#infoTable tbody'); var hTr; $('#infoTable thead').append(hTr = $('<tr>')); // Headers for (var h = 0; h < result.headers.length; h++) { hTr.append($('<th>', { text: result.headers[h] })) } // Body for (var d in result.data) { var data = result.data[d]; $('#infoTable tbody').append($('<tr>') .append($('<td>', { text: data.RecyclableID })) .append($('<td>', { text: data.Name })) .append($('<td>', { text: data.RecyclableType })) ) } }, error: function(xhr, status, error) { console.log('请求错误信息:', xhr.responseText); console.log('当前传递的apikey:', sessionStorage.getItem("apikey")); } })
排查校验步骤
- 先在浏览器控制台执行
console.log(sessionStorage.getItem("apikey")),确认存储的apikey存在且和Insomnia中使用的完全一致,避免apikey过期或者存储错误 - 打开浏览器开发者工具的「网络」面板,找到该接口的请求记录,核对请求头或者查询参数中的apikey和Insomnia中的传值格式完全一致
- 如果是跨域请求,需要确认服务端已经允许前端自定义的
apikey头跨域,否则会触发CORS错误
内容的提问来源于stack exchange,提问作者Flow
相关产品推荐
相关产品推荐

