使用Twitter API的Jquery Ajax 401响应

时间:2016-11-02 04:04:40

标签: javascript jquery json ajax twitter

我们使用邮递员发送请求,其中包含适当的Authorization参数和我们的访问密钥,它返回我们正在寻找的JSON,但是在我们的javascript中,我们尝试使用ajax和jsonp发送请求但是获得了401尝试这样做时的响应错误。这是我们的代码。

shopButton.click(() => {
            // The getJSON function initiates a connection to the web service.
            $.ajax({
                url: 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=adidasalerts&count=3',
                dataType: 'jsonp',
                headers: {
                    'Authorization':'Bearer REDACTED',
                }
                success: function(dataWeGotViaJsonp){
                    console.log(dataWeGotViaJsonp)
                }
            });
        });

我们知道我们的访问令牌有效,因为我们可以使用Postman发送请求。有没有人有任何想法?在我们尝试使用$ .getJSON之前,我们仍然遇到跨域域错误。

1 个答案:

答案 0 :(得分:1)

jquery ajax并不理解属性Authorization的含义 - 您需要使用headers属性或beforeSend回调添加Authorization标头来设置标头 - 见documentation

$.ajax({
    headers: {Authorization: 'Bearer REDACTED'},
    url: 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=adidasalerts&count=3',
    dataType: 'jsonp',
    success: function (dataWeGotViaJsonp) {
        console.log(dataWeGotViaJsonp)
    }
});