javascript-在Google Drive API上简单上传的身份验证问题
作者:互联网
我正在尝试将文件上传到我的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密钥.
谢谢!
解决方法:
如果您使用的是oauth2令牌,则必须在Authorization标头中指定Bear和auth令牌,例如
httpRequest.setRequestHeader(“ Authorization”,“ Bearer MY_AUTH_KEY”);
标签:google-drive-api,javascript 来源: https://codeday.me/bug/20191123/2066134.html