Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery JSONP ajax, authentication header not being set

Tags:

I'm trying to make an ajax request to the google contacts API with the following setup:

$.ajax({   url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all",   dataType: 'jsonp',   data: {     alt: 'json-in-script'   },   headers: {     'Authorization': 'Bearer ' + token   },   success: function(data, status) {     return console.log("The returned data", data);   } }); 

But the Authentication header doesn't seem to get set. Any ideas?

The request

like image 573
David Tuite Avatar asked Sep 15 '11 15:09

David Tuite


2 Answers

I had the same problem recently. Try this:

$.ajax({   url: "https://www-opensocial.googleusercontent.com/api/people/@me/@all",   dataType: 'jsonp',   data: {     alt: 'json-in-script'   },   success: function(data, status) {     return console.log("The returned data", data);   },   beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }  }); 

EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request

like image 174
Andrew Church Avatar answered Sep 18 '22 17:09

Andrew Church


When authentication is needed in a cross domain request, you must use a proxy server of some sort.

Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.

like image 20
Dangladesh Avatar answered Sep 16 '22 17:09

Dangladesh