jQuery带token请求接口返回401错误解决过程记录

有一个第三方接口需要token验证身份,于是我在jQuery Ajax请求中加入了token:

$.ajax({
    url: "/api/v1/wuliu/queryTrace",
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", localStorage.token);
    },            
    success:function(data){
        console.log(data);
    }
})

结果接口返回401错误,这说明身份验证出了问题,通过抓包我确认了请求头中有Authorization:

引用内容 引用内容
Authorization: "bearer;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoi5pmu6YCa55So5oi3IiwidW5pcXVlX25hbWUiOiJ5eWRsLTEzMjU1MDQ0NzA0IiwidXNlcmlkIjoiMTUyODM1NDY5MDM0ODIyNDUxMiIsImlzcyI6InJlc3RhcGl1c2VyIiwiYXVkIjoiMDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjYiLCJleHAiOjE5ODIyODAxMDMsIm5iZiI6MTY2NjkyMDEwM30.zuMzltEA8Z-V4msD_R_QZpaV-KLz4Ffop0-YLUgceZU"

不知道哪里出了问题,尝试将token直接写到代码中:

$.ajax({
    url: "/api/v1/wuliu/queryTrace",
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", "bearer;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoi5pmu6YCa55So5oi3IiwidW5pcXVlX25hbWUiOiJ5eWRsLTEzMjU1MDQ0NzA0IiwidXNlcmlkIjoiMTUyODM1NDY5MDM0ODIyNDUxMiIsImlzcyI6InJlc3RhcGl1c2VyIiwiYXVkIjoiMDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjYiLCJleHAiOjE5ODIyODAxMDMsIm5iZiI6MTY2NjkyMDEwM30.zuMzltEA8Z-V4msD_R_QZpaV-KLz4Ffop0-YLUgceZU");
    },            
    success:function(data){
        console.log(data);
    }
})

结果接口正常返回了,两者有什么区别吗?再次抓包,Authorization是这样子的:

引用内容 引用内容
Authorization: bearer;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoi5pmu6YCa55So5oi3IiwidW5pcXVlX25hbWUiOiJ5eWRsLTEzMjU1MDQ0NzA0IiwidXNlcmlkIjoiMTUyODM1NDY5MDM0ODIyNDUxMiIsImlzcyI6InJlc3RhcGl1c2VyIiwiYXVkIjoiMDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjYiLCJleHAiOjE5ODIyODAxMDMsIm5iZiI6MTY2NjkyMDEwM30.zuMzltEA8Z-V4msD_R_QZpaV-KLz4Ffop0-YLUgceZU

通过比较发现,前者Authorization的值多了一对引号,在控制台直接输出token,也是多了一对引号:



知道了原因,对代码稍做修改,替换删除掉引号:

$.ajax({
    url: "/api/v1/wuliu/queryTrace",
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", localStorage.token.replace(/"/g, ""));
    },            
    success:function(data){
        console.log(data);
    }
})

问题解决!

评论: 0 | 引用: 0 | 查看次数: 1734
发表评论
登录后再发表评论!