How to include header in ajax request?

I need to include the header with the update token in the ajax call on the YouTube api. I am trying to send a deletion request to delete a movie that I have in my account. This is my ajax call that fires when a button is clicked

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 get 401 (unauthorized) erorr when I return, and it seems that I need to include my access token in the call. I played with the google api playground looking at the request and response, and this shows how the "request" is sent

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 this request, it looks like there are headers that are sent with the request that contain the access token. That must be why I get error 401. How do I include these headers in my ajax request so that my access token is passed along with the request? Thanks

+1
3

, :

    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');
        }
    }); 
+4

beforeSend request.setRequestHeader. .

P.S. ?

+2

Try adding paracter 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');
    }
});
0
source

All Articles