【问题标题】:Simple API call with "Bearer" token Authorization using Ajax使用 Ajax 的“Bearer”令牌授权的简单 API 调用
【发布时间】:2022-11-17 11:35:40
【问题描述】:

我的问题是我无法使用 Ajax 从 API 获取数据。

我正在使用 JWT 令牌进行身份验证,当我从 Postman 调用 API 时,我成功获取了数据。

但是,当使用 ajax 调用 API 时,会检测到 ERR_ABORTED 401(未授权)错误。 这是代码:

$.ajax({
    type: "GET",
    url: API_URL,
    dataType: 'jsonp',
    contentType: "application/json",
    headers: {
        "Cache-Control": "no-cache",
        "Authorization": "Bearer " + access_token,
    },
    data: {}, 
    success: function(resp){
        console.log(resp)
    }, 
    error: function(error){
    }    
})

另外,当我复制并使用 POSTMAN 生成的代码 sn-p 时,我得到了同样的错误。

我为此搜索了很多答案并应用了它们,但它对我不起作用。

有人可以帮忙吗?

先感谢您。

【问题讨论】:

    标签: ajax api jwt


    【解决方案1】:

    您在第 5 行有错误...它应该是dataType: 'json'

    解决方案:

    $.ajax({
        type: "GET",
        url: API_URL,
        dataType: 'json',
        contentType: "application/json",
        headers: {
            "Cache-Control": "no-cache",
            "Authorization": "Bearer " + access_token,
        },
        data: {}, 
        success: function(resp){
            console.log(resp)
        }, 
        error: function(error){
        }    
    });
    

    【讨论】:

    • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写出好的答案的信息in the help center
    猜你喜欢
    • 2014-11-18
    • 2021-02-20
    • 1970-01-01
    • 2015-04-24
    • 2021-04-15
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多