我正在使用 Express JS 服务器
执行AWS MWS API
。根据 MWS
文档,_GET_REMOTE_FULFILLMENT_ELIGIBILITY_
返回 Excel 文件对象。
我在node js
中创建了API,但我无法获得正确的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;
}
}
最佳答案
终于,我找到了解决办法。我更改了调用 API 的方法,如下所示,并获得了正确的 excel 文件。
我使用了node-fetch,然后通过node-fetch向Amazon 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;
}
关于node.js - 如何从AWS MWS API json响应下载.xlsx文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67786734/