David Parks David Parks - 1 month ago 24
Javascript Question

Jquery Ajax 401 response using Twitter API

We are using postman to send the request with the proper parameter of Authorization and our access key which returns the JSON we are looking for, however in our javascript we are trying to send a request using ajax and jsonp but are getting a 401 response error when attempting to do so. Here is our code.

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)
}
});
});


We know our access token works because we can send requests just fine using Postman. Does anyone have any ideas? Before we were attempting to use $.getJSON but we kept getting cross origin domain errors.

Answer

jquery ajax doesn't understand what you mean by the property Authorization - you need to add the Authorization header using the headers property or the beforeSend callback to set the header - see 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)
    }
});