1

I need to include a header with a refresh token in an ajax call to the YouTube api. I am trying to send a delete request, to delete a movie I have on my account. This is my ajax call that fire on button click

jQuery.ajax({
        type: 'DELETE',
        // must set api key
        url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
        success: function() {
        alert('your video has been deleted');
        },
        error: function() {
        alert('error processing your requst');
        }
    }); 

I am receiving a 401 (unauthorized) erorr on return and it seems that I need to include my access token in the call. I was playing around with the google api playground looking at the request and response and this is what shows as the 'Request' being sent out

DELETE https://www.googleapis.com/youtube/v3/videos?id=3242343&key={YOUR_API_KEY}

Authorization:  Bearer "access token"
X-JavaScript-User-Agent:  Google APIs Explorer

Now from that request it looks like the there are headers that are being sent with the request, which hold the access token. This must be why I am getting a 401 error. How can I include those headers into my ajax request, so that my access token is passed along with the request? Thanks

EHerman
  • 1,852
  • 7
  • 32
  • 52

3 Answers3

4

I was able to pass along a header using this code below:

    jQuery.ajax({
        type: 'DELETE',
        // must set api key
        url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID +'&key=api_key_here',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer access_token_here');},
        success: function() {
        alert('your video has been deleted');
        },
        error: function() {
        alert('error processing your request');
        }
    }); 
Jonathan Morales Vélez
  • 3,030
  • 2
  • 30
  • 43
EHerman
  • 1,852
  • 7
  • 32
  • 52
  • What is the difference between using the beforeSend function to contain the header and adding "headers: { 'Authorization': 'Bearer access_token_here' 'Content-Type': 'application/json'}" into the ajax call? – Sachin Kainth Nov 17 '16 at 11:33
2

You can use beforeSend method and request.setRequestHeader. Take a look at the official documentation here.

P.S. should I post it as a comment?

Mahdi
  • 9,247
  • 9
  • 53
  • 74
0

Try add the paramenter data.

jQuery.ajax({
    type: 'DELETE',
    data: 'key=' + {YOUR_API_KEY},
    // must set api key
    url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
    success: function() {
    alert('your video has been deleted');
    },
    error: function() {
    alert('error processing your requst');
    }
});
Alexandre Mendes
  • 119
  • 1
  • 1
  • 11