Gmail API会通过批量请求返回400 BadRequest

时间:2016-03-15 14:54:15

标签: javascript meteor google-api

我正在尝试使用以下内容向gmail发送批量http请求(在带有Meteor / HTTP的服务器上):

batchGetMessages = (accessToken, ids) => {
  let userId = 'me';
  let url = `https://www.googleapis.com/batch`;
  let boundary = `batch_message_request`;
  let body = ``;

  _.each(ids, (id) => {
    body = `${body}
    --${boundary}
    Content-Type: application/http

    GET /gmail/v1/users/${userId}/messages/${id.id}?format=metadata&fields=id%2Cpayload
    `
  });

  body = `${body}
    --${boundary}--`

  let options = {
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': `multipart/mixed; boundary="${boundary}"`,
    },
    content: body,
  };

  let data = HTTP.post(url, options);
  console.log('data: ', data);
}

身体的绳子看起来像这样:

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15375be281102d3d?format=metadata&fields=id%2Cpayload

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15366f87db6bdfeb?format=metadata&fields=id%2Cpayload

--batch_message_request
Content-Type: application/http

GET /gmail/v1/users/me/messages/15365d62f152dea2?format=metadata&fields=id%2Cpayload

--batch_message_request--

我的请求总是返回400 Bad Request错误。我已经检查了类似的问题,但还没有能够使这个工作:

Generating HTTP multipart body for file upload in JavaScript

Gmail REST api batch support for getting messages

Batch request - 400 bad request response

任何帮助或建议将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,400 BadRequest错误似乎是由字符串模板中的换行符空格引起的。删除空白使一切正常:

...
/* 
  the lack of whitespace is impotant in the folllowing string template:
*/
  _.each(ids, (id) => {
    body = `${body}
--${boundary}
Content-Type: application/http

GET /gmail/v1/users/${userId}/messages/${id.id}? format=metadata&fields=id%2Cpayload`
  });

  body = `${body}
--${boundary}--`;
...

可能有一种更好的方法来维护代码缩进并消除空白,但我还没有找到它。