首页 > 解决方案 > 使用NodeJS(ExpressJS)将文件上传到谷歌驱动器时需要登录错误

问题描述

我正在开发 NodeJS API 以将多图像上传到 Google 驱动程序,当用户创建电子书(包括名称、描述和 ebookPhoto)时,我正在使用 ExpressJS 编写 Rest API。使用multer-google-drive它是一个 multer 中间件存储引擎,用于将文件上传到 Google Drive。我也按照此链接将图片上传到 Google Drive 以将文件上传到 Google Drive。以下是我所做的这些步骤。

1- 第 1 步:我运行以下代码以获取“token.json”文件。

const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/drive.file']; // This SCOPE is for upload file
const credentials = require('./credentials.json');
const TOKEN_PATH = 'token.json';

const getAccessToken = (oAuth2Client, resolve, reject) => {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return reject('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return reject(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      resolve(oAuth2Client);
    });
  });
}

2- 第 2 步我运行下面的代码来获得授权:

const {google} = require('googleapis');
const credentials = require('./credentials.json')
const token = require('./token.json');


const authorize = () => {
    const { client_secret, client_id, redirect_uris } = credentials.installed;
    const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

    if (token && typeof token === 'object') {
      return oAuth2Client.setCredentials(token);
    }
    return null
}


var drive = google.drive({version: 'v3', auth: authorize});

3- 第 3 步是使用 multer-google-drive 上传文件的步骤,我这样做:

// Upload lên storage của google
var gDriverUpload = multer({
    storage: GoogleDriveStorage({
      drive: drive,
      parents: 'id-parents', // this is id of folder in google drive
      fileName: function (req, file, cb) {
        let filename = `ebook-${file.originalname}`;
        cb(null, filename);
      }
    })
  })

这是我的 API 路线:

// Create and upload to google driver
EbookRouter.post('/gdriver', gDriverUpload.array('ebookPhoto', 5), ebookController.createEbook);

因此,当我调用这样的 API 来上传电子书信息(包括 ebookPhoto)时,我得到的错误名称是:“需要登录”

localhost:3009/api/ebook/gdriver

详细错误如下:

POST /api/ebook/gdriver 500 1478.509 ms - 354
Error: Login Required
    at Gaxios._request (E:\google_api_uploader\node_modules\gaxios\build\src\gaxios.js:85:23)
    at process._tickCallback (internal/process/next_tick.js:68:7)

请帮我找出这个问题。非常感谢

标签: node.jsexpressfile-uploadgoogle-drive-apigoogle-api-nodejs-client

解决方案


推荐阅读