如何从 AWS MWS API json 响应下载 .xlsx 文件?
Posted
技术标签:
【中文标题】如何从 AWS MWS API json 响应下载 .xlsx 文件?【英文标题】:How to download .xlsx file from AWS MWS API json response? 【发布时间】:2021-08-19 12:39:11 【问题描述】:我正在使用Express JS server
来执行AWS MWS API
。根据MWS
文档,_GET_REMOTE_FULFILLMENT_ELIGIBILITY_
返回 excel 文件对象。
我在node js
中创建了 API,但我无法获得正确的 excel。我下载的 excel 文件中有奇怪的字符。
附件中可以看到下载的excel文件
const getRemoveFulfillmentEligibilityDataCon = async(req,res) =>
const mwsRequestData =
Version: '2009-01-01',
Action: 'GetReport',
'SellerId': 'MWS_SELLER_ID',
'MWSAuthToken': 'MWS_AUTH_TOKEN',
ReportId: 'XXXXXXXXXXXXXX',
;
try
const response = await amazonMws.reports.search(mwsRequestData);
/* make the worksheet */
var ws = XLSX.utils.json_to_sheet(response.data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws);
XLSX.writeFile(wb, "sheetjs.xlsx");
return response;
catch (error)
console.log('error ', error);
return error;
【问题讨论】:
【参考方案1】:最后,我找到了解决方案。我更改了调用 API 的方法,如下所示,我得到了一个正确的 excel 文件。
我使用node-fetch,然后通过node-fetch向亚马逊MWS发送请求。
node-fetch 正确解码内容编码 (gzip/deflate) 并自动将字符串输出转换为 UTF-8。
var param = ;
param['AWSAccessKeyId'] = 'xxxxxxxxxxxxx';
param['Action'] = 'GetReport';
param['MarketplaceId'] = 'xxxxxxxxxxxxx';
param['SellerId'] = 'xxxxxxxxxxxxx';
param['ReportId'] = 'xxxxxxxxxxxxx';
param['ItemCondition'] = 'New';
param['SignatureMethod'] = 'HmacSHA256';
param['SignatureVersion'] = '2';
param['Timestamp'] = encodeURIComponent(new Date().toISOString());
param['Version'] = '2009-01-01';
secret = 'xxxxxxxxxxxxx';
var url = [];
for(var i in param)
url.push(i+"="+param[i])
url.sort();
var arr = url.join("&");
var sign = 'POST\n'+'mws.amazonservices.com\n'+'/Reports/2009-01-01\n'+arr;
const crypto = require('crypto');
let s64 = crypto.createHmac("sha256", secret).update(sign).digest('base64');
let signature = encodeURIComponent(s64);
var bodyData = arr+"&Signature="+signature;
const fileName = "sheetjs.xlsx";
var apiResponse = await fetch('https://mws.amazonservices.com/Reports/2009-01-01',
method: 'POST',
body: bodyData,
headers:
'content-type': 'application/x-www-form-urlencoded',
'Accept': '',
,
)
.then(res =>
const dest = fs.createWriteStream('./'+fileName);
res.body.pipe(dest).on('finish', function()
//console.log('done');
return 'Status': 200, 'Message': 'Downloaded';
);
)
.catch(error =>
console.log('Request failed', error);
);
return apiResponse;
【讨论】:
以上是关于如何从 AWS MWS API json 响应下载 .xlsx 文件?的主要内容,如果未能解决你的问题,请参考以下文章
如何将JSON数据添加到HTML AWS lambda响应主体?