【问题标题】:Multipart/mixed request for google drive bulk deletion using request npm package使用请求 npm 包对谷歌驱动器批量删除的多部分/混合请求
【发布时间】:2022-01-19 12:03:19
【问题描述】:

我试图使用 REST API 从谷歌驱动器中批量删除文件。所以我正在构建批量删除请求的请求,我能够使用类似的请求框架方法Bulk delete files on Google Drive with raw XMLHttpRequest 来实现删除,但我试图在不发送正文而不是在请求对象中发送多部分数组的情况下实现这一点。我收到以下响应正文的错误 400

<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>

这是我的请求对象,它失败

const _multipart = []
arrayOfFileIds.forEach((current) => {
    const obj = {
        body: 'Content-Type: application/http\n\n' +
            'DELETE https://www.googleapis.com/drive/v3/files/' +
            current + '\nAuthorization: Bearer ' + authToken
    }
    _multipart.push(obj)
})

const requestOptions = {
    url: 'https://www.googleapis.com/batch/drive/v3',
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/mixed'
    },
    multipart: _multipart
}

下面的请求对象正在工作

const boundary = 'END_OF_PART'
const separation = '\n--' + boundary + '\n'
const ending = '\n--' + boundary + '--'
const requestBody = arrayOfFileIds.reduce((accum, current) => {
    accum += separation +
        'Content-Type: application/http\n\n' +
        'DELETE https://www.googleapis.com/drive/v3/files/' +
        current +
        '\nAuthorization: Bearer ' + authToken
    return accum
}, '') + ending


const requestOptions = {
    url: 'https://www.googleapis.com/batch/drive/v3',
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/mixed; boundary=' + boundary

    },
    body: requestBody
    multipart: _multipart
}

【问题讨论】:

    标签: rest request google-drive-api multipart multipart-mixed-replace


    【解决方案1】:

    修改点:

    • 访问令牌可以包含在请求标头中。
    • 将每个批处理请求的Content-Type 放到body 之外。

    当这些点反映到你的脚本中时,它变成如下。

    修改脚本:

    const _multipart = [];
    arrayOfFileIds.forEach((current) => {
      const obj = {
        "Content-Type": "application/http",
        body: "DELETE https://www.googleapis.com/drive/v3/files/" + current + "\n",
      };
      _multipart.push(obj);
    });
    
    const requestOptions = {
      url: "https://www.googleapis.com/batch/drive/v3",
      method: "POST",
      headers: {
        "Content-Type": "multipart/mixed",
        Authorization: "Bearer " + authToken,
      },
      multipart: _multipart,
    };
    

    注意:

    • 当我测试上面修改的脚本时,没有出现错误。可以删除文件。您在测试上述脚本时,如果出现错误,请再次确认脚本和访问令牌。

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多