问题
I am trying to use apiGoogle Node.js client library to access the Google Drive API so I can upload some files to my drive account.
My code so far:
var drive = google.drive({ version: 'v3' });
drive.apiKey = "API_KEY"
drive.setScope = "https://www.googleapis.com/auth/drive.file"
drive.files.create({
resource: {
name: 'text.text',
mimeType: 'text/plain',
parents:['1ATscm2nsE9KpjA66iXHB9jnMrbyik7PP']
},
media: {
mimeType: 'text/plain',
body: fs.createReadStream('files/text.text')
}
});
Errors:
errors:
[ { domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' } ] }
Can anybody help to resolve this issue?
回答1:
It looks like you are missing the authorization. First you need to turn on the Drive API in the developers console. Then you can use it with the following code replaced by your credentials.
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
var drive = google.drive({
version: 'v3',
auth: oauth2Client
});
You can check out this section on github if you have more questions about this.
Or if you haven't you can check out their docs here.
回答2:
You may refer with this thread. Make sure that you are sending access_token={your oauth2 access token}
and not key={your key}
for an access token. You may check this documentation for more information.
来源:https://stackoverflow.com/questions/48637563/how-to-use-api-key-to-access-the-google-drive