我正在尝试将文件上传到我的Google云端硬盘文件空间,我正在使用以下代码:
var httpRequest = new XMLHttpRequest();
var url_goto = "https://www.googleapis.com/upload/drive/v2/files?uploadType=media";
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState==4 && httpRequest.status==200) {
Firebug.Console.log(httpRequest.responseText);
} else if (httpRequest.readyState==4 && httpRequest.status==401) {
Firebug.Console.log(httpRequest.responseText);
} else {
Firebug.Console.log('Other status: ' + httpRequest.readyState + ', ' + httpRequest.status);
}
};
var s = 'Test string';
httpRequest.open('POST', url_goto, true);
httpRequest.setRequestHeader('Content-Type', 'text/plain');
httpRequest.setRequestHeader('Content-Length', s.length);
httpRequest.setRequestHeader('Authorization', 'MY_AUTH_KEY');
httpRequest.send(s);
问题是我有以下输出:
"Other status: 1, 0"
"Other status: 1, 0"
"Other status: 2, 401"
"Other status: 3, 401"
...并抛出异常:
"{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}"
任何人都可以帮助我理解为什么身份验证不起作用? 我正在使用从我的Google API控制台检索到的API密钥,在简单API访问部分下。
谢谢!
答案 0 :(得分:3)
如果您使用的是oauth2令牌,则必须在授权标头中指定Bear和auth令牌,如
httpRequest.setRequestHeader(“授权”,“Bearer MY_AUTH_KEY”);