【问题标题】:I am trying to access the GDrive api after authentication with passport js. However, I am getting this error -我正在尝试在使用护照 js 进行身份验证后访问 GDrive api。但是,我收到此错误 -
【发布时间】:2022-06-16 21:04:07
【问题描述】:

错误 - API 返回错误:错误:未设置访问权限、刷新令牌、API 密钥或刷新处理程序回调。

我想做的是-

app.get("/getinfo", (req,resp)=>{
        const oauth2Client = new google.auth.OAuth2(myClientID, myClientSecret, redirectURL )
        var data="";
        fs.readFile("token.json", function(err, dat) {
            if (err) throw err;
             data=JSON.parse(dat);
            oauth2Client.setCredentials({
                'access_token': data.token
            });
        });
         listFiles(oauth2Client);
         resp.send("Getting drive files");
     });

其中“token.json”包含通过护照 js 成功验证后收到的身份验证令牌。 “listFiles”函数是-

function listFiles(auth) {
     console.log(auth);
     const drive = google.drive({version: 'v3', auth});
     drive.files.list({
       pageSize: 10,
       fields: 'nextPageToken, files(id, name)',
     }, (err, res) => {
         console.log("inside drive api call");
       if (err) return console.log('The API returned an error: ' + err);
       const files = res.data.files;
       if (files.length) {
         console.log('Files:');
         files.map((file) => {
           console.log(`${file.name} (${file.id})`);
         });
       } else {
         console.log('No files found.');
       }
     });
   }

有人可以帮助我了解如何使此功能正常工作。我的目标是在成功验证后读取一个人的云端硬盘文件列表。我已经检查了验证所需的范围。

【问题讨论】:

    标签: node.js oauth-2.0 google-drive-api passport.js access-token


    【解决方案1】:

    传递给fs.readFile 的回调在调用listFiles 之后执行,因此您传递oauth2Client 时没有设置访问令牌。

    您至少有以下选项来修复它:

    • readFile 回调中调用listFiles(在setCredentials 之后)
    • fs.readFile 替换为fs.readFileSync,这样您就不需要回调了
    • 使用 fs/promises 和 async/await 代替回调

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多