如何在Ajax请求中包含头文件? [英] How to include header in ajax request?

查看:633
本文介绍了如何在Ajax请求中包含头文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在YouTube api的ajax调用中包含带有刷新令牌的标头。我正尝试发送删除请求,删除我在我的帐户中的电影。这是我的ajax调用点击按钮点击

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

我在收到401(未经授权)的erorr时,似乎需要包含我的访问权限令牌。我正在玩Google api游乐场,看着请求和响应,这就是'Request'被发送出去的情况。

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

现在根据该请求,它看起来像是头部是与请求一起被发送,其中持有访问令牌。这一定是我得到401错误的原因。如何将这些头文件包含到我的ajax请求中,以便我的访问令牌与请求一起传递?谢谢

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

推荐答案

我可以使用下面的代码传递一个头文件:

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

这篇关于如何在Ajax请求中包含头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆