0

我试图使用rest API从谷歌驱动器中批量删除文件。因此,我正在构建批量删除请求的请求,我能够使用类似的请求框架方法使用原始 XMLHttpRequest 在 Google Drive 上批量删除文件来实现删除,但我试图在不发送正文而不是发送多部分数组的情况下实现这一点请求对象。我收到以下响应正文的错误 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
}
4

1 回答 1

3

修改点:

  • 访问令牌可以包含在请求标头中。
  • 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,
};

笔记:

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

参考:

于 2021-12-16T12:43:29.890 回答