我正在尝试向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 错误请求错误。我已经检查了类似的问题,但尚未能够使其正常工作:
在 JavaScript 中为文件上传生成 HTTP 多部分正文
Gmail REST API 批处理支持接收邮件
批处理请求 - 400 错误请求响应
任何帮助或建议将不胜感激。谢谢!
好吧,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}--`;
...
可能有一种更奇特的方法来维护代码缩进并消除空格,但我还没有寻找它。